// 定义 action 类型
const ActionTypes = {
INCREMENT: 'INCREMENT',
DECREMENT: 'DECREMENT'
};
// action 创建函数
function increment() {
return { type: ActionTypes.INCREMENT };
}
function decrement() {
return { type: ActionTypes.DECREMENT };
}
// reducer
function counterReducer(state = { count: 0 }, action) {
switch (action.type) {
case ActionTypes.INCREMENT:
return { count: state.count + 1 };
case ActionTypes.DECREMENT:
return { count: state.count - 1 };
default:
return state;
}
}
// 创建 store
function createStore(reducer) {
let currentState = undefined;
const listeners = [];
function getState() {
return currentState;
}
function dispatch(action) {
currentState = reducer(currentState, action);
listeners.forEach(listener => listener());
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
dispatch({ type: '@@redux/INIT' });
return {
getState,
dispatch,
subscribe
};
}
// 创建 store
const store = createStore(counterReducer);
// 订阅 store 变化
const unsubscribe = store.subscribe(() => {
console.log('Current State:', store.getState());
});
// 发起一些 action
store.dispatch(increment());
store.dispatch(increment());
store.dispatch(decrement());
// 停止订阅
unsubscribe();
function kcreateStore(reducer) {
var list = []
var state = reducer(undefined,{})
function subscribe(callback) {
list.push(callback)
}
function dispatch(action) {
state = reducer(state, action)
for (var i in list) {
list[i] && list[i]()
}
}
function getState() {
return state
}
return {
subscribe,
dispatch,
getState
}
}
redux源码代码实现
最新推荐文章于 2024-06-10 22:18:41 发布