function reducer(state={num:0}, action) {
switch(action.type) {
case "add":
return {
...state,
num:state.num+=5
}
case "minus":
return {
...state,
num:state.num-=1
}
}
}
function createStore(reducer,initValue) {
let state = initValue;
let arr = []
// 派发一个任务
function dispatch(action) {
state = reducer(state,action)
return action
}
// 获取state的值
function getState() {
arr.forEach(item =>item())
return state;
}
// 更新state的值
function subscribe(fn) {
arr.push(fn)
}
return {
dispatch,
getState,
subscribe
}
}
let store = createStore(reducer,initValue={num:0})
let dis = store.dispatch({type:"add"})
console.log(store.getState());
手动实现react-createStore方法
最新推荐文章于 2023-07-17 17:54:25 发布