redux的簡單實(shí)現(xiàn)原理
function createStore(reducer) {
let state;
let getState = () => {
return JSON.parse(JSON.stringify(state))
};
let listeners = [];
let subScribe=fn => {
listeners.push(fn);
return fn => {
listeners.filter(item => item!==fn)
}
};
let dispatch = action => {
state = reducer(state,action);
listeners.forEach(item => item());
};
dispatch({});
return {getState,dispatch,subScribe};
}
export {createStore}
- action的寫法
import * as Types from '../action-types';
export default {
add(number) {
return { type: Types.ADD, number };
},
};
//這樣直接導(dǎo)出埃儿,當(dāng)做mapDispatch傳給connect茅诱,需要dispatch的時(shí)候調(diào)用一下this.props.add就會(huì)觸發(fā)自動(dòng)調(diào)用dispatch