创建redux基本步骤
1.新建action-type.js文件(操作类型)
基本结构如下:
export const xxx = 'xxxx'
2.新建reducer.js文件
主要是结构:
const xxxx = (state,action) => {
switch (action.type) {
case xxx:
//操作
break
}
}
- 创建store ,多个reduce人可以合并使用
基本用法:
combineReducers:用于合并多个reducer;
例如:需要明确键值对
const reducer = combineReducers(
{ count:count,
other:other
})
createStore:创建store;
例如:
const store= createStore(reducer)
在页面上引用store
主要分为页面单独引用和全局引用,下面将一一介绍两种情况的用法和注意事项;
- 注意事项:使用subscribe 监听store变化;使用store.getState90获取数据
- 页面引用(直接在页面上引入store)
获取后的count,直接在页面上渲染使用,也可以直接dispatch更改count的值
全局引用store
注意事项:
- hooks中使用useSelector()获取store的值;
- 使用useDispatch获取dispatch
- 使用provider组件包括全局;
app.js || xxx.js
import { Provider } from 'react-redux'
import store from "../../store/index";
function () {
returrn {
<Provider store={store}> // 往下级组件传store
</ xxxxxx>
</Provider>
}
}
子组件:
child.js || xxx.js
app.js || xxx.js
import {useSelector,useDispatch} from 'react-redux'
function (props) {
const count = useSelector(state => state.count); // 接收store的值
const other = useSelector(state => state.other);
const dispatch = useDispatch(); // 接收dispatch
returrn {
<>
<div onClick={() => dispatch({type:'ADD'})}>text页面</div>
<div onClick={() => dispatch({type:'NEW',text:'88888'})}>other页面</div>
</>
}
}