安装

  1. yarn add redux

使用

Reducer

  • 一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
  • 是一个纯函数。也就是说,只要是同样的输入,必定得到同样的输出。因此 Reducer 函数里面不能改变 State,必须返回一个全新的对象,

    1. const reducer = function (state, action) {
    2. // ...
    3. return new_state;
    4. };

    createStore

  • 创建一个 store,接受一个函数 Reducer

    1. import { createStore } from 'redux';
    2. const store = createStore(Reducer);

    getState

  • 获取 store 里的数据

    1. store.getState()

    action

  • Action 是一个对象。其中的 type 属性是必须的,表示 Action 的名称。其他属性可以自由设置,社区有一个规范 可以参考。

    1. const action = {
    2. type: 'ADD_TODO',
    3. payload: 'Learn Redux'
    4. };

    Action Creator

  • View 要发送多少种消息,就会有多少种 Action。如果都手写,会很麻烦。可以定义一个函数来生成 Action,这个函数就叫 Action Creator。

    1. const ADD_TODO = '添加 TODO';
    2. function addTodo(text) {
    3. return {
    4. type: ADD_TODO,
    5. text
    6. }
    7. }
    8. const action = addTodo('Learn Redux');

    dispatch

  • store.dispatch() 是 View 发出 Action 的唯一方法。

    1. import { createStore } from 'redux';
    2. const store = createStore(fn);
    3. store.dispatch({
    4. type: 'ADD_TODO',
    5. payload: 'Learn Redux'
    6. });

    subscribe

  • Store 允许使用 store.subscribe 方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。

    1. import { createStore } from 'redux';
    2. const store = createStore(reducer);
    3. store.subscribe(listener);
  • 只要把 View 的更新函数(对于 React 项目,就是组件的render方法或setState方法)放入listen,就会实现 View 的自动渲染。

    store.subscribe 方法返回一个函数,调用这个函数就可以解除监听

    1. let unsubscribe = store.subscribe(() =>
    2. console.log(store.getState())
    3. );
    4. unsubscribe();

    总结

    1. 创建一个 reducer,两个参数 state action

    2. 将 reducer 作为参数创建一个 store

    2. dispatch 一个 action 对象,reducer 会接受 action 返回一个新 state

    2. 监听 state,su bscribe 订阅一个回调,state 变化时触发

    问题

  • 隔代组件间传递数据需要层层传递,使用 react-reducer 解决