Redux简介

1,332 阅读2分钟

Redux

参考: redux.js.org/

Redux是一个为JavaScript app设计的可预测的状态管理工具

Redux不需要其他插件支持,Redux本身就可以实现日志记录、热加载、时间旅行、通用应用程序的记录和重放。

开发要点

整个app的state是存在一个store里的对象树,只能通过提交一个action来改变状态树。reducer是用来描述action改变state树的细节。

import { createStore } from 'redux'

/**
 * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, an object,
 * or even an Immutable.js data structure. The only important part is that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * In this example, we use a `switch` statement and strings, but you can use a helper that
 * follows a different convention (such as function maps) if it makes sense for your
 * project.
 */
function counter(state = 0, action) {
  switch (action.type) {
  case 'INCREMENT':
    return state + 1
  case 'DECREMENT':
    return state - 1
  default:
    return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.

store.subscribe(() =>
  console.log(store.getState())
)

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

我们是通过指定具体操作对应的action对象直接返回新的state,而不是直接修改旧的state。reducer是用来描述每一个action具体改变state的过程。

Redux跟flux最大的不同在于,Redux没有一个dispatcher也没有多个store。相反,它只有一个根store,绑定了一个根reducer。随着app变大,我们不是增加store,而是将根reducer切割成不同独立负责不同state模块的子reducer。跟React app设计一样,表面上好像是一个大组件,但实际上是由不同的小组件组成。

Redux是针对大型并且复杂的app设计的,它可以跟踪每一个state改变对应的action,甚至通过记录用户会话,我们可以通过重播action来还原用户的实际操作