三大原则
整个应用的state存储在一个对象中,且该对象只存在一个store中
唯一改变state的方式就是触发action
编写reducer,接收之前的state和action,并返回新的state
实现Redux
有时候看代码模拟实现可以更直观的了解内部机制,当然能力足够建议查看redux源码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {});
return { getState: () => currentState, dispatch: (action) => { currentState = yourReducer(currentState, action);
listeners.forEach((listener) => { listener(); }); }, subscribe: (newListener) => { listeners.push(newListener);
const unsubscribe = () => { listeners = listeners.filter((l) => l !== newListener); };
return unsubscribe; } }; };
|