手把手实现一个 Redux,从原理到应用
2024-02-01 05:36:12
Redux 是一个专注于状态管理的 JavaScript 库,它遵循 Flux 架构,基于单向数据流的思想,让状态的可预测性更强,从而帮助我们更轻松地管理应用程序的状态。
入门 Redux
为了更好地理解 Redux 的工作原理,我们先从一个简单的计数器应用入手。这个应用的功能非常简单,它只有一个按钮,点击按钮时计数器会增加 1。
1. 初始化 Redux Store
首先,我们创建一个 Redux store 来存储应用程序的状态。Store 是一个对象,它包含应用程序的所有状态,并且可以被应用程序中的任何部分访问。
const store = createStore(reducer);
2. 定义 Reducer
Reducer 是一个纯函数,它接收两个参数:之前的状态和一个 action,然后返回一个新的状态。在我们的计数器应用中,reducer 的代码如下:
function reducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
default:
return state;
}
}
Reducer 根据 action.type 来决定如何更新 state。在我们的例子中,只有 'INCREMENT' 这一种 action,它会让 state 增加 1。
3. 定义 Action
Action 是一个包含了 action 类型和 payload 的对象。在我们的计数器应用中,action 的代码如下:
const incrementAction = { type: 'INCREMENT' };
4. Dispatch Action
当我们想要更新 state 时,我们需要 dispatch 一个 action。Dispatch action 会调用 reducer,然后 reducer 返回一个新的 state,store 就会被更新。
store.dispatch(incrementAction);
5. 订阅 Store
为了在 state 更新时获取通知,我们可以订阅 store。当 state 更新时,订阅者就会被调用。
store.subscribe(() => {
console.log(store.getState());
});
实现一个简化版的 Redux
理解了 Redux 的基本原理后,我们就可以自己实现一个简化版的 Redux。
1. 创建 Store
class Store {
constructor(reducer) {
this.reducer = reducer;
this.state = reducer(undefined, {});
this.subscribers = [];
}
dispatch(action) {
this.state = this.reducer(this.state, action);
this.subscribers.forEach(subscriber => subscriber());
}
subscribe(subscriber) {
this.subscribers.push(subscriber);
}
}
2. 创建 Reducer
function reducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
default:
return state;
}
}
3. 创建 Action
const incrementAction = { type: 'INCREMENT' };
4. 使用 Store
const store = new Store(reducer);
store.subscribe(() => {
console.log(store.getState());
});
store.dispatch(incrementAction);
结语
通过本文,我们从原理到应用,一步步构建了一个属于你自己的 Redux 库,让你对 Redux 的工作原理和使用方法有了更深入的了解。
Redux 是一个非常强大的状态管理库,它可以帮助我们管理大型应用程序的状态。如果你想要学习如何使用 Redux,那么本文是一个很好的起点。