快速复习 Flux 和 Redux

Flux

Flux 就是一个设计模式,用于管理数据传递流程。其核心概念为单一方向性的数据流。

Flux 由下列 3 个角色组成:

使用 3 者搭配 View(React) 来开发 Client-Side 网页应用程序。

See the Pen oQNzjx by andyyou (@andyyou) on CodePen.

Redux

Redux 是给 JavaScript 应用程序使用的一种状态管理容器

使用 createStore 建立一个全应用程序唯一的 storestore 须使用 reducerPure Function)来变更内部的 state

执行状态变更须发送 actionstore.dispatch(action)),一个 action 只是一个单纯的对象须包含 type 属性用来描述变更行为,对应的行为在 reducer 中实现。

Redux 由下列几个单元组成:

  • Store:整个应用程序只有一个 Store

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import { createStore } from 'redux';
    const store = createStore(reducer);

    store.getState();

    let unsubscribe = store.subscribe(() => {
    console.log(store.getState());
    });
    // 解除
    unsubscribe();
  • Action:action 是一个单纯的对象,须包含 type 属性。要变更 state 必须要发送 action

    1
    2
    3
    4
    5
    6
    const action = {
    type: 'ADD_TODO',
    text: 'Learn Redux',
    };
    // 发送 action 的方式
    store.dispatch(action);
  • Reducer:发送了 action 之后,须变更 state ,使 state 变更的计算过程称为 reducerreducer 为一函数接收 actionstate 回传一个新的计算后的 state

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    const todos = function(state, action) {
    switch(action.type) {
    case 'ADD_TODO':
    return [
    ...state,
    action.text,
    ];
    default:
    return state;
    }
    }

See the Pen rQNRVY by andyyou (@andyyou) on CodePen.

原文引用 大专栏  https://www.dazhuanlan.com/2019/08/27/5d64c95952286/


猜你喜欢

转载自www.cnblogs.com/petewell/p/11418654.html