// 导入redux - 并解构出创建store的函数 - createStore
import {configureStore} from '@reduxjs/toolkit'
// 定义源数据
const state = {
name: '张三',
age: 12
}
// 定义reducer - 修改state数据的纯函数 - 修改就需要依赖 state的副本 和 action,这个函数是需要两个参数
// 语法
// const reducer = (state的副本, action规则) => {
// return 新的副本
// }
// 将state赋值给newState, 在redux内部会帮我们处理一个深拷贝操作,保证newState和state数据一致,但不是同一个地址
const reducer = (newState = state, action) => {
// 待处理
if(action.type === 'zizeng') {
newState.age = state.age + action.num
}
// 返回新的副本
return newState
}
console.log(typeof(reducer));//function
// 创建仓库 - 调用createStore函数,将reducer当参数传递进去
const store = configureStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
// 导出仓库
export default store
在执行上面这段代码时报错reducer必须为函数或者对象,但是log出来我的reducer就是个函数。
加个大括号解决,大意了,下不为例。