返回

深入理解 Redux 源码之 createStore 篇

前端

Redux 及其重要性

Redux 是一种状态管理库,用于 JavaScript 应用程序。它以一种可预测且可重复的单向数据流方式管理应用程序的状态。Redux 的主要优点是,它使应用程序的状态易于理解和调试,并且它提供了时间旅行调试的功能。

Redux 由两个主要部分组成:

  1. Store :Store 是一个对象,它保存着应用程序的状态。
  2. Actions :Actions 是对象,它们了状态的变化。

createStore 方法

createStore 方法是 Redux 的重要组成部分,用于创建 Redux store。createStore 方法接收两个参数:

  1. Reducer :Reducer 是一个纯函数,它接收当前状态树 state 和 发起的 action,并返回一个新的状态树。
  2. Preloaded State :Preloaded State 是一个可选参数,它指定了 store 的初始状态。

createStore 方法返回一个 Redux store 对象,该对象提供以下方法:

  1. dispatch :dispatch 方法用于向 store 发送 actions。
  2. getState :getState 方法用于获取 store 的当前状态。
  3. subscribe :subscribe 方法用于监听 store 的状态变化。

createStore 的工作原理

createStore 方法的工作原理如下:

  1. createStore 方法首先创建一个 store 对象。
  2. store 对象保存着应用程序的状态。
  3. 当向 store 发送一个 action 时,store 会使用 reducer 函数来计算新的状态。
  4. store 会将新的状态广播给所有订阅者。

如何使用 createStore 方法

要使用 createStore 方法,你需要首先创建一个 reducer 函数。reducer 函数是一个纯函数,它接收当前状态树 state 和 发起的 action,并返回一个新的状态树。

创建好 reducer 函数后,你就可以使用 createStore 方法来创建 Redux store。

const store = createStore(reducer);

你也可以向 createStore 方法传递一个可选的 preloadedState 参数,来指定 store 的初始状态。

const store = createStore(reducer, preloadedState);

创建好 Redux store 后,你就可以使用 dispatch 方法来向 store 发送 actions。

store.dispatch(action);

你也可以使用 getState 方法来获取 store 的当前状态。

const state = store.getState();

你还可以使用 subscribe 方法来监听 store 的状态变化。

store.subscribe(() => {
  console.log(store.getState());
});

总结

在这一篇文章中,我们学习了 Redux 的 createStore 方法,以及如何使用它来创建 Redux store。我们还学习了 createStore 方法的工作原理,以及如何使用它来管理应用程序的状态。