动手实现一个最简单的 redux
redux 的主要 API 集中在 createStore 函数返回值中,以下这个迷你的 redux 只简单实现 createStore、dispatch、subscribe、getState 方法,如下:
const createStore = function(reducer, initialState){
let currentState = undefined;
if(initialState) {
currentState = initialState;
}
let currentReducer = reducer;
let listeners = [];
return {
getState() {
return currentState;
},
dispatch(action) {
if(!currentState){
currentState = currentReducer(currentState, action);
}
currentState = currentReducer(currentState, action);
listeners.forEach((item) => {
item();
});
return this;
},
subscribe(fn) {
listeners.push(fn);
}
}
};
测试代码:
let reducer = function(state, action) {
if(!state) {
return {counter: 0};
}
switch(action.type) {
case 'ADD':
return {counter: state.counter+1};
case 'DEL':
return {counter: state.counter-1};
default:
return state;
}
};
let store = createStore(reducer);
store.subscribe(function(){
console.log('before1')
});
store.subscribe(function() {
console.log('before2')
});
store.dispatch({
type:'ADD'
});
console.log(store.getState());
store.dispatch({
type: 'ADD'
});
console.log(store.getState());
store.dispatch({
type: 'DEL'
});
console.log(store.getState());
运行结果:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论