redux的源码解读(一)
首先是自己实现的简易版的redux。主要是对着API按照自己的思路实现了一遍的初版,没有任何的异常处理
代码语言:javascript复制function createStore(reducer, initialState) {
let currentState = initialState,
listeners = [];
function getState() {
//返回当前的state
return currentState;
}
function dispatch(action) {
let prestate = currentState;
currentState = reducer(prestate, action);
listeners.forEach((item) => item());
}
function subscribe(callback) {
//返回值是取消订阅
let hasUnsubscribe = false;
listeners.push(callback);
return function unsubscribe() {
if (!hasUnsubscribe) {
let index = listeners.indexOf(callback);
listeners = listeners.splice(index, 1);
}
}
}
function replaceReducer(newReducer) {
reducer = newReducer;
}
return {getState, dispatch, subscribe, replaceReducer}
}
function testReducer(state = {sum:0}, action) {
switch (action.type) {
case 'ADD':
return {
...state,
sum: state.sum 1
}
case 'DEC':
return {
...state,
sum: state.sum - 1
}
default:
return state;
}
}
const store = createStore(testReducer);
//测试
console.log('begin',store.getState());//begin undefined
store.subscribe(() => console.log('触发了action',store.getState()));
store.dispatch({type:'ADD'});//触发了action {sum: 1}
console.log('end',store.getState());//end {sum: 1}
这样的话是有问题的,就是我们不去dispatch的时候,初始的state是undefined的,显然不符合redux的API的要求。在redux API中,我们的初始state可以是从reducer或者从createStore中传入的。然而我们的代码中没从createStore中传入state的话在没有dispatch任何东西之前state是undefined的(从上面的log信息)。。。所以,创建store实例的时候自己先dispatch一次。从redux的源码中可以看到初始化的时候dispatch({ type: ActionTypes.INIT })
。这个ActionTypes.INIT
是一个随机数。我们做出一点修改即可。
function createStore(reducer, initialState) {
let currentState = initialState,
listeners = [];
dispatch('initial');//初始化的时候dispatch下
function getState() {
//返回当前的state
return currentState;
}
function dispatch(action) {
let prestate = currentState;
currentState = reducer(prestate, action);
listeners.forEach((item) => item());
}
function subscribe(callback) {
//返回值是取消订阅
let hasUnsubscribe = false;
listeners.push(callback);
return function unsubscribe() {
if (!hasUnsubscribe) {
let index = listeners.indexOf(callback);
listeners = listeners.splice(index, 1);
}
}
}
function replaceReducer(newReducer) {
reducer = newReducer;
}
return {getState, dispatch, subscribe, replaceReducer}
}
function testReducer(state = {sum:0}, action) {
switch (action.type) {
case 'ADD':
return {
...state,
sum: state.sum 1
}
case 'DEC':
return {
...state,
sum: state.sum - 1
}
default:
return state;
}
}
const store = createStore(testReducer);
console.log('begin',store.getState());
store.subscribe(() => console.log('触发了action',store.getState()));
store.dispatch({type:'ADD'});
console.log('end',store.getState());
至此我们的简易版redux的createStore就实现了。当然我们没有做任何的异常处理hhh。后面就进行其它部分的探讨,