1、为什么要用reducer去修改数据,直接在state或者store上修改不是更简单吗?
结论是:
- 1、数据流可控
- 2、因为数据流只能函数调用(dispatch对应等reducer)修改state,所以把修改数据局限在一定的范围,不像之前可以随意 更改对象的属性和值,这也是面向对象的一个思想,封装,不能谁都能对你的对象有操作权限,防止轻易的修改数据
- 3、基于第二点,函数的调用就会产生函数调用栈,而直接修改对象是不会有这个栈的,所以可以在reducer里面打断点,或者console,看看谁调用了自己,从而排查出异常的修改
2、实现一个单一store的createstore函数,解释逻辑
function createStore (state, stateChanger) {const listeners = []const subscribe = (listener) => listeners.push(listener)const getState = () => stateconst dispatch = (action) => {state = stateChanger(state, action) // 覆盖原对象listeners.forEach((listener) => listener())}dispatch({})return { getState, dispatch, subscribe }}
就上面代码举个例子大家就知道逻辑了
// 按照我们平时写reducer的写法,写一个简单的reducerconst reducer = function(state={a:2}, action){switch (action.type) {case 'A':return { ...state, a: 5 }default:return state;}}// 接着我们create一个storeconst store = createStore(null, reducer)// 这里注意,我们没有传state,我们在createStore代码里有一条dispatch({})// 因此就初始化了statestore.getState() // 获取初始化后的statestore.dispatch({ type: 'A' }) // 使用dispatch来更新statestore.subscribe(() => {//更新视图的逻辑})
