推荐答案
// www.javascriptcn.com code example
class Store {
constructor(reducer, initialState) {
this.reducer = reducer;
this.state = initialState;
this.listeners = [];
}
getState() {
return this.state;
}
dispatch(action) {
this.state = this.reducer(this.state, action);
this.listeners.forEach(listener => listener());
}
subscribe(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter(l => l !== listener);
};
}
}
// 示例 reducer
function counterReducer(state = { count: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
// 创建 store
const store = new Store(counterReducer, { count: 0 });
// 订阅状态变化
store.subscribe(() => {
console.log('State changed:', store.getState());
});
// 派发 action
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });本题详细解读
1. Store 类
Store 类是状态管理的核心,它包含以下几个关键方法:
constructor(reducer, initialState): 初始化 store,接收一个 reducer 函数和初始状态。getState(): 返回当前的状态。dispatch(action): 派发一个 action,调用 reducer 更新状态,并通知所有订阅者。subscribe(listener): 订阅状态变化,返回一个取消订阅的函数。
2. Reducer 函数
reducer 是一个纯函数,接收当前状态和一个 action,返回新的状态。在这个例子中,counterReducer 处理了两个 action 类型:INCREMENT 和 DECREMENT,分别用于增加和减少计数器的值。
3. 使用示例
- 首先创建了一个
Store实例,传入counterReducer和初始状态{ count: 0 }。 - 然后通过
subscribe方法订阅状态变化,每次状态变化时都会打印新的状态。 - 最后通过
dispatch方法派发INCREMENT和DECREMENTaction,观察状态的变化。
4. 总结
这个简单的状态管理实现展示了 Redux 的核心思想:通过一个中心化的 store 来管理应用的状态,并通过 reducer 函数来处理状态的变化。虽然这个实现非常简单,但它涵盖了状态管理的基本概念,可以作为理解更复杂状态管理库的基础。