Redux 学习笔记

141 阅读4分钟

1. 应用场景

  • 某个组件的状态,需要共享
  • 某个状态需要在任何地方都可以拿到
  • 一个组件需要改变全局状态
  • 一个组件需要改变另一个组件的状态

2.设计思想

  1. Web 应用是一个状态机,视图与状态是一一对应的。
  2. 所有的状态,保存在一个对象里面。

3. 基本概念和API

1. Store

  • Store 就是保存数据的地方,整个应用只能有一个 Store
  • Redux 提供createStore这个函数,用来生成 Store
import { createStore } from 'redux';
const store = createStore(fn);

2. State

  • State 就是 Store 某一时刻的数据
  • 当前时刻的 State,可以通过store.getState()拿到。
import { createStore } from 'redux';
const store = createStore(fn);

const state = store.getState();

3. Action

  • State 的变化,会导致 View 的变化
  • State 的变化必须是 View 导致
  • Action 就是 View 发出的通知,表示 State 应该要发生变化了
  • Action 是一个对象。其中的type属性是必须的,表示 Action 的名称。其他属性可以自由设置,社区有一个规范可以参考。
const action = {
  type: 'ADD_TODO',
  payload: 'Learn Redux'
};

Action 描述当前发生的事情。改变 State 的唯一办法,就是使用 Action。

4. Action Creator

可以定义一个函数来生成 Action,这个函数就叫 Action Creator。

const ADD_TODO = '添加 TODO';

// action creator
function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

const action = addTodo('Learn Redux');

5. store.dispatch()

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

import { createStore } from 'redux';
const store = createStore(fn);

store.dispatch({
  type: 'ADD_TODO',
  payload: 'Learn Redux'
});

6. Reducer

Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 根据不同 Action 做不同计算的过程就叫做 Reducer。

Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。

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

例子:

const defaultState = 0;
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'ADD':
      return state + action.payload;
    default: 
      return state;
  }
};

const state = reducer(1, {
  type: 'ADD',
  payload: 2
});

reducer函数根据不同的action类型做return不同的结果

实际应用中,Reducer 函数不用像上面这样手动调用,store.dispatch方法会触发 Reducer 的自动执行。

Store 需要知道 Reducer 函数,做法就是在生成 Store 的时候,将 Reducer 传入createStore方法。

import { createStore } from 'redux';
const store = createStore(reducer);  // here

store.dispatch({
  type: 'ADD_TODO',
  payload: 'Learn Redux'
});

7. 纯函数

Reducer 函数最重要的特征是,它是一个纯函数。也就是说,只要是同样的输入,必定得到同样的输出

对纯函数的约束:

  • 不得改写参数
  • 不能调用系统 I/O 的API
  • 不能调用Date.now()或者Math.random()等不纯的方法,因为每次会得到不一样的结果

8. store.subscribe()

监听 State 的变化,执行相应监听函数

import { createStore } from 'redux';
const store = createStore(reducer);

let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
);

unsubscribe();  // 解除监听

4. Store 的实现

  1. Store 提供三个重要方法,用来获取 State、发布和监听
import { createStore } from 'redux';
let { subscribe, dispatch, getState } = createStore(reducer);
  1. createStore方法还可以接受第二个参数,表示 State 的最初状态
// 如果提供了这个参数,它会覆盖 Reducer 函数的默认初始值。
let store = createStore(todoApp, window.STATE_FROM_SERVER)
  1. createStore的简单实现

  2. const createStore = (reducer) => {
      let state;
      let listeners = [];
    
      const getState = () => state;
    
      const dispatch = (action) => {
        state = reducer(state, action);
        listeners.forEach(listener => listener());
      };
    
      const subscribe = (listener) => {
        listeners.push(listener);
        return () => {
          listeners = listeners.filter(l => l !== listener);
        }
      };
    
      dispatch({});
    
      return { getState, dispatch, subscribe };
    };
    

5. Reducer 的拆分

const chatReducer = (state = defaultState, action = {}) => {
  const { type, payload } = action;
  switch (type) {
    case ADD_CHAT:
      return Object.assign({}, state, {
        chatLog: state.chatLog.concat(payload)
      });
    case CHANGE_STATUS:
      return Object.assign({}, state, {
        statusMessage: payload
      });
    case CHANGE_USERNAME:
      return Object.assign({}, state, {
        userName: payload
      });
    default: return state;
  }
};

<==>

const chatReducer = (state = defaultState, action = {}) => {
  return {
    chatLog: chatLog(state.chatLog, action),
    statusMessage: statusMessage(state.statusMessage, action),
    userName: userName(state.userName, action)
  }
};

<==>

import { combineReducers } from 'redux';

const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
})

combineReducers方法将多个子 Reducer 合并成一个大的函数。

const reducer = combineReducers({
  a: doSomethingWithA,
  b: processB,
  c: c
})

// 等同于
function reducer(state = {}, action) {
  return {
    a: doSomethingWithA(state.a, action),
    b: processB(state.b, action),
    c: c(state.c, action)
  }
}

你可以把所有子 Reducer 放在一个文件里面,然后统一引入。

import { combineReducers } from 'redux'
import * as reducers from './reducers'

const reducer = combineReducers(reducers)

combineReducer的简单实现:

const combineReducers = reducers => {
  return (state = {}, action) => {
    return Object.keys(reducers).reduce(
      (nextState, key) => {
        nextState[key] = reducers[key](state[key], action);
        return nextState;
      },
      {} 
    );
  };
};

6. 工作流程

整体流程:

  1. 用户发Action
  2. Store 自动调用 Reducer,返回新的State
  3. State 一旦有变化,Store 就会调用监听函数
  4. 监听函数通过store.getState()得到当前状态,重新渲染 View
// 1
store.dispatch(action);

// 2
let nextState = todoApp(previousState, action);

// 3
store.subscribe(listener);

// 4
function listerner() {
  let newState = store.getState();
  component.setState(newState);   
}

7. 实例:计数器

const Counter = ({ value, onIncrement, onDecrement }) => (
  <div>
  <h1>{value}</h1>
  <button onClick={onIncrement}>+</button>
  <button onClick={onDecrement}>-</button>
  </div>
);

const reducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT': return state + 1;
    case 'DECREMENT': return state - 1;
    default: return state;
  }
};

const store = createStore(reducer);

const render = () => {
  ReactDOM.render(
    <Counter
      value={store.getState()}
      onIncrement={() => store.dispatch({type: 'INCREMENT'})}
      onDecrement={() => store.dispatch({type: 'DECREMENT'})}
    />,
    document.getElementById('root')
  );
};

render();
store.subscribe(render);

参考:

  1. www.ruanyifeng.com/blog/2016/0…
  2. cn.redux.js.org/