Action和Reducer的编写
前面我们已经实现了一个从store中获取数据,并将数据在组件<Todolist/>
中展示的案例
接下来我们要创建action, dispatch action到store,然后转发给reducer去处理
action的本质就是一个js对象: {type:string,data:any}
const addItem = (item) => {
const action = {
type:'add_item_action',
data: item
}
store.dispatch(action)
}
const changeInputValue = (value) =>{
const action = {
type:'change_inputvalue_action',
value
}
//dispatch之后,store就能拿到state的数据,然后转发给reducer处理
store.dispatch(action)
}
reducer处理: store处理数据有个规则,不能在state上直接改数据,你需要先深拷贝一下state,然后在新的state上修改,最后把新的state返回回去
const defaultState = {
inputValue:'',
list:['1','2']
}
//reducer本质就是一个函数
const reducer = (state=defaultState, action) => {
//对state进行深拷贝
const newState = JSON.parse(JSON.stringify(state))
switch (action.type) {
case 'change_inputvalue_action':
newState.inputValue = action.value
return newState
case 'add_item_action':
newState.list.push(action.data)
newState.inputValue = ''
//清空inputValue
return newState
default:
break;
}
return state
}
export default reducer
此时store里的数据确实是更新了,但是组件状态却没更新,原因是没有打通store->view
的闭环
我们说组件能感知store数据的变化而自动更新组件,这种感知其实是调用了store.subscribe(func)
方法
useEffect(()=>{
//当感知到store发生改变
store.subscribe(()=>{
const state = store.getState()
setList(state.list)
setInputValue(state.inputValue)
})
})
到此redux完整的工作流顺利跑通, 完整的demo