这里主要研究通过action(借书人说的话)传递给store(管理员),store再从reducer(记录本)查询数据,reducer将查询到的数据返回给store,最后store再返回给组件(借书用户)。最终要实现当reducers数据发生变化的时候,组件的数据也跟着变化
1.当组件的input框输入内容发生改变时,自动调用handleInputChange,通过store.dispatch()将数据发送给store(管理员)
handleInputChang (e){
const action = {
type: 'chang_input_value',
value: e.target.value
}
store.dispatch(action);
}
2.store会自动将previousState与接收到的action传递给reducers(记录本)
3.reducers接收store传递过来的数据进行判断,如果为真将其新数据返回给store
//reducer可以接收state的数据,但是不可以修改
export default (state = defaultState , action) => {
if(action.type === 'chang_input_value') {
const newState = JSON.parse(JSON.stringify(state)) //深拷贝
newState.inputValue = action.value;
return newState;
}
return state;
}
4.组件订阅store的改变,只要store改变,就触发该方法
//订阅store的改变,只要store改变,就触发该方法
store.subscribe(this.handleStoreChange)
将其写到custructor中
5.将最新的store数据获取到
handleStoreChange () {
this.setState(store.getState())
}