创建store文件夹
结构:
- store
- store.js
- index.js
创建store.js
const UseStore = {
SAVE_RESULT: 'save_result', // 定义动作变量名
defaultResultInfo: { // 设置默认值
1: ''
},
action: { // 转换动作为包括动作类型及内容参数的函数
save: (result) => {
return {
type: UseStore.SAVE_RESULT,
resultInfo: result
}
}
},
reducer: (state = UseStore.defaultResultInfo, action) => { // 修改state的唯一方法,根据action.type来进行相应的修改操作
switch (action.type) {
case UseStore.SAVE_RESULT:
for (const key in action.resultInfo) {
if (Object.prototype.hasOwnProperty.call(action.resultInfo, key)) {
const element = action.resultInfo[key];
state[key] = element
}
}
return state
default:
return state
}
}
}
export default UseStore
创建index.js
import {combineReducers, createStore} from 'redux'
import UserStore from "./store";
// 合并多个reducer
const reducers = combineReducers( // 将多个state进行合并
{resultInfo: UserStore.reducer}
)
// 创建store
const store = createStore(reducers) // 创建仓库
export {store} // 导出仓库, 后续其他组件可以进行调用来获取仓库信息
其他组件调用仓库存储内容
import { store } from '../../store/index'
import UserStore from "../../store/store";
store.getState() // 获取仓库存储内容
store.dispatch(action) // 修改仓库存储内容,action为需要存进仓库的内容,可调用UserStore。action.save()方法来统一格式