创建仓库
import {legacy_createStore, combineReducers,compose,applyMiddleware} from "redux"
import reduxThunk from "redux-thunk"
import handleXxxx from "./XxxxStatus/reducer"
// 组合各个模块的reducer
const reducers = combineReducers({
handleXxxx
})
// 创建数据仓库
// window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() 为了让浏览器正常使用redux-dev-tools插件
// const store = legacy_createStore(reducers,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
// 判断有没有__REDUX_DEVTOOLS_EXTENSION_COMPOSE__这个模块
let composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose //rt
// 把仓库数据,浏览器redux-dev-tools,还有reduxThunk插件关联在store中
const store = legacy_createStore(reducers,composeEnhancers(applyMiddleware(reduxThunk)));
export default store
1. `store`对象中包含了几个属性:
- `state`:用于存放数据的属性。你可以在这里定义需要追踪的数据字段。
- `actions`:用于存放同步方法的属性。你可以在这里定义处理状态更新逻辑的方法。
- `asyncActions`:用于存放异步方法的属性。你可以在这里定义处理异步操作的方法。
- `actionNames`:一个空的对象,用于存放动作名称。
2. 使用`let actionNames = {}`创建一个空的`actionNames`对象。
3. 通过`for...in`循环遍历`store.actions`对象的属性,在每次迭代中将属性名(方法名)添加到`actionNames`对象中。这样,`actionNames`对象将包含与`store.actions`对象中方法名称相同的属性和值。
4. 将`actionNames`对象赋值给`store`对象的`actionNames`属性。
5. 最后,通过`export default`将`store`对象导出,以便在其他模块中可以轻松引入和使用这个状态对象。
const store = {
state:{
// 放数据
},
actions:{
// 放同步方法
},
asyncActions:{
// 放异步方法
},
actionNames:{}
}
let actionNames = {}
for(let key in store.actions){
actionNames[key] = key
}
store.actionNames=actionNames;
export default store
1. 首先,通过`import handler from "./index"`语句引入了一个名为`handler`的模块。
2. 创建了一个名为`reducer`的函数,它接收两个参数:`state`和`action`。`state`参数默认值为`{...handler.state}`,这里使用扩展运算符将`handler.state`对象的属性拷贝到新的对象中。
3. 创建了一个新的状态副本:`let newState = JSON.parse(JSON.stringify(state))`。通过将`state`对象转换成字符串,然后再解析成新的对象,来创建一个深度拷贝。
4. 使用`for...in`循环遍历`handler.actionNames`对象的属性。`handler.actionNames`是在`handler`模块中定义的一个包含所有动作名称的对象。
5. 如果当前遍历到的动作名称(通过`action.type`获取)与`handler.actionNames`中的某个动作名称匹配,则调用对应动作名称的方法。例如,`handler.actions[handler.actionNames[key]](newState,action)`会调用`handler.actions`对象中与匹配的动作名称对应的方法,并传入`newState`和`action`作为参数。
6. 在循环结束后,返回更新后的`newState`作为函数的结果。
7. 最后,通过`export default`将`reducer`函数导出,使其可供其他模块使用。
import handler from "./index"
let reducer = (state = {...handler.state},action:{type:string})=>{
let newState = JSON.parse(JSON.stringify(state))
for(let key in handler.actionNames){
if(action.type===handler.actionNames[key]){
handler.actions[handler.actionNames[key]](newState,action);
break;
}
}
return newState
}
export default reducer
获取数据和修改数据
获取数据
xxx:state.handlexxx.xxx
//修改数据
dispatch({type:"xxx",val:xxx})