入门 Redux

Redux 是 JavaScript 应用的状态容器,提供可预测的状态管理。

可以让你开发出行为稳定可预测的应用,运行于不同的环境(客户端、服务器、原生应用),并且易于测试。不仅于此,它还提供超爽的开发体验,比如有一个时间旅行调试器可以编辑后实时预览

Redux 除了和 React 一起用外,还支持其它界面库。它体小精悍(只有2kB,包括依赖),却有很强大的插件扩展生态。

安装

Redux Toolkit

Redux Toolkit 是我们官方推荐的编写 Redux 逻辑的方法。它包含了 Redux 核心,并包含我们认为对于构建 Redux 应用必不可少的软件包和功能。Redux Toolkit 建立在我们建议的最佳实践中,简化了大多数 Redux 任务,防止了常见错误,并使编写 Redux 应用程序更加容易。

RTK 包含了有助于简化许多常见场景的工具,包括 配置 Store创建 reducer 并编写 immutable 更新逻辑, 甚至还包含 一次性创建整个 State 的 “切面”

无论你是一个完全的新手想要开发第一个 Redux 应用,还是经验老到的老手想要简化已有应用,Redux Toolkit 都能帮你写出更好的 Redux 代码.

Redux Toolkit 提供 NPM 软件包,安装方式如下:

  1. # NPM
  2. npm install @reduxjs/toolkit
  3. # Yarn
  4. yarn add @reduxjs/toolkit

创建一个 React Redux 应用

官方推荐的创建 React Redux 新应用的方式是使用 官方 Redux+JS 模版,它基于 Create React App,它利用了 Redux Toolkit 和 Redux 与 React 组件的集成.

  1. npx create-react-app my-app --template redux

Redux 核心库

Redux 核心库同样有 NPM 软件包,安装方式如下:

  1. # NPM
  2. npm install redux
  3. # Yarn
  4. yarn add redux

还有一个使用方式是通过预编译的 UMD 包,定义了 window.Redux 这个全局变量。UMD 包可以通过 <script> tag 直接使用。

想要获取更多信息,查看 安装.

基础示例

应用的整体全局状态以对象树的方式存放于单个 store。 唯一改变状态树(state tree)的方法是创建 action,一个描述发生了什么的对象,并将其 dispatch 给 store。 要指定状态树如何响应 action 来进行更新,你可以编写纯 reducer 函数,这些函数根据旧 state 和 action 来计算新 state。

  1. import { createStore } from 'redux'
  2. /**
  3. * This is a reducer - a function that takes a current state value and an
  4. * action object describing "what happened", and returns a new state value.
  5. * A reducer's function signature is: (state, action) => newState
  6. *
  7. * The Redux state should contain only plain JS objects, arrays, and primitives.
  8. * The root state value is usually an object. It's important that you should
  9. * not mutate the state object, but return a new object if the state changes.
  10. *
  11. * You can use any conditional logic you want in a reducer. In this example,
  12. * we use a switch statement, but it's not required.
  13. */
  14. function counterReducer(state = { value: 0 }, action) {
  15. switch (action.type) {
  16. case 'counter/incremented':
  17. return { value: state.value + 1 }
  18. case 'counter/decremented':
  19. return { value: state.value - 1 }
  20. default:
  21. return state
  22. }
  23. }
  24. // Create a Redux store holding the state of your app.
  25. // Its API is { subscribe, dispatch, getState }.
  26. let store = createStore(counterReducer)
  27. // You can use subscribe() to update the UI in response to state changes.
  28. // Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
  29. // There may be additional use cases where it's helpful to subscribe as well.
  30. store.subscribe(() => console.log(store.getState()))
  31. // The only way to mutate the internal state is to dispatch an action.
  32. // The actions can be serialized, logged or stored and later replayed.
  33. store.dispatch({ type: 'counter/incremented' })
  34. // {value: 1}
  35. store.dispatch({ type: 'counter/incremented' })
  36. // {value: 2}
  37. store.dispatch({ type: 'counter/decremented' })
  38. // {value: 1}

你需要使用 action 这个普通对象来描述发生了什么,而不是直接改变 state。然后,编写一个名为 reducer 的特殊函数,来决定如何基于 action 来更新整个应用的状态树。

在典型的Redux应用程序中,只有一个 store 以及一个根 reducer 函数。随着应用程序的增长,您可以将根 reducer 拆分为较小的 reducer,分别在状态树的不同部分上进行操作。这就像在 React 应用程序中只有一个根组件一样,但是它是由许多小组件组成的。

对于简单的计数器应用来说,这种架构看起来过度设计,但是这种模式的优点在于它可以很好地扩展到大型和复杂的应用程序。还可以基于此设计出功能非常强大的开发者工具,因为可以跟踪每个 action 以及状态变更。你可以记录用户会话并仅通过重播每个 action 来重现它们。

Redux Toolkit 示例

Redux Toolkit 简化了编写 Redux 逻辑和设置 store 的过程。 使用 Redux Toolkit,相同的逻辑如下所示:

  1. import { createSlice, configureStore } from '@reduxjs/toolkit'
  2. const counterSlice = createSlice({
  3. name: 'counter',
  4. initialState: {
  5. value: 0
  6. },
  7. reducers: {
  8. incremented: state => {
  9. // Redux Toolkit allows us to write "mutating" logic in reducers. It
  10. // doesn't actually mutate the state because it uses the Immer library,
  11. // which detects changes to a "draft state" and produces a brand new
  12. // immutable state based off those changes
  13. state.value += 1
  14. },
  15. decremented: state => {
  16. state.value -= 1
  17. }
  18. }
  19. })
  20. export const { incremented, decremented } = counterSlice.actions
  21. const store = configureStore({
  22. reducer: counterSlice.reducer
  23. })
  24. // Can still subscribe to the store
  25. store.subscribe(() => console.log(store.getState()))
  26. // Still pass action objects to `dispatch`, but they're created for us
  27. store.dispatch(incremented())
  28. // {value: 1}
  29. store.dispatch(incremented())
  30. // {value: 2}
  31. store.dispatch(decremented())
  32. // {value: 1}

Redux Toolkit 使我们可以编写更精短的代码,更易于阅读,同时仍然遵循同样的 Redux 规范和数据流。

学习 Redux

我们有多种资源可帮助您学习Redux。

Redux 基础教程

Redux 基础教程 是一个“自上而下”的教程,使用推荐的最新 API 和最佳实践来教“如何以正确的方式使用 Redux”。建议从那里开始。

Redux 进阶教程

Redux 进阶教程 是一个“自下而上”的教程,该教程从最初的原理开始,没有任何抽象地讲授“Redux 工作原理”,以及 Redux 标准规范存在背后的原因。

附加教程

其他资源

帮助和讨论

The #redux channel of the Reactiflux Discord community is our official resource for all questions related to learning and using Redux. Reactiflux is a great place to hang out, ask questions, and learn - come join us!

You can also ask questions on Stack Overflow using the #redux tag.

If you have a bug report or need to leave other feedback, please file an issue on the Github repo

你需要使用 Redux 吗?

虽然 Redux 是一个很有加载的管理状态工具,但还是要考虑下它是否适合你的场景。不要仅仅因为有人说过应该使用 Redux 而使用 - 应该花一些时间来了解使用它的潜在好处和取舍

当遇到如下问题时,建议开始使用 Redux:

  • 你有很多数据随时间而变化
  • 你希望状态有一个唯一确定的来源(single source of truth)
  • 你发现将所有状态放在顶层组件中管理已不可维护

有关如何使用Redux的更多想法,请参见: