The difference with redux:
It is relatively simple, without writing a subscription, it is actually a simplified version of Redux.
The focus is on providers (Provider) and connectors (connect), and two mappings (stateToProps, dispatchToProps)
Install react-redux, redux
npm install --save react-redux
npm install --save redux
Use react-redux to achieve accumulation
1) Create a store warehouse
src>store>index.js:
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
src>store>reducer.js:
const defaultState = {
num: 0
}
//导出(一开始的时候,state作为形参,一开始没有值,所以让他等于defaultState)
export default (state = defaultState, action) => {
return state
}
2) Delete all files under src, and create index.js and Add.js under src
Add.js:
import React, { Component } from 'react'
import { connect } from 'react-redux'
class Add extends Component {
render() {
return (
<div>
<div>num: {this.props.num}</div>
<button onClick={this.props.addnum}>增加</button>
</div>
)
}
}
// stateToProps是一种映射关系,把原来的state映射成组件中的props属性
const stateToProps = (state) => {
return {
num: state.num
}
}
// dispatchToProps也是一种映射,用于传递并修改数据,这里要返回一个对象并包含一个事件
const dispatchToProps = (dispatch) => {
return {
addnum() {
const action = {
type: 'add_fn',
value: 1
}
dispatch(action)
}
}
}
// 导出连接器
export default connect(stateToProps, dispatchToProps)(Add)
index.js:
import React from 'react'
import { createRoot } from 'react-dom/client'
import { Provider } from 'react-redux'
import store from './store'
import Add from './Add'
const root = createRoot(document.getElementById('root'))
root.render(
// Provider (提供器)组件
<Provider store = {store}>
<Add />
</Provider>
)
* Then all components in the Provider provider can get the data in the store.
3) Then in reducer.js, the accumulation is realized by triggering the action.
const defaultState = {
num: 0
}
//导出(一开始的时候,state作为形参,一开始没有值,所以让他等于defaultState)
export default (state = defaultState, action) => {
//对原本的state做一次深拷贝。
//reducer只能接收state,不能直接对它进行改变
var newState = JSON.parse(JSON.stringify(state))
//通过判断action的type,确定是否需要修改
switch (action.type) {
case 'add_fn':
newState.num += action.value;
break;
default:
break;
}
return newState
}