学习笔记:Flux与Redux

2021-04-29  本文已影响0人  双鱼子曰1987

一、概述

Flux和Redux 是React生态中重要的组成部分,个人觉得,它们核心功能就是将页面 和 数据+逻辑 解耦,将数据+逻辑 进一步抽象组件化。

二、Flux

Flux是一套架构模式,而不是代码框架。所谓的架构模式,是一套方法论,指导系统如何更好搭建。例如模块如何划分?模块间如何通信?Web开发中的MVC模式,其实就是架构模式。

1、四大核心部分
2、架构设计
flux-overview.png

Flux参考

具体的Demo和用法参考一下教程,很详细了~
ReacFlux教程

三、Redux

1、什么Redux?

Redux 是 JavaScript 状态容器, 提供可预测化的状态管理。那什么是可以预测化,我的理解就是根据一个固定的输入,必然会得到一个固定的结果。
Redux是进化Flux,它是在Flux架构模式指导下生成的代码框架,也进一步进行架构约束设计。

2、Redux的核心思想

借用阮一峰大神的话:Redux 的设计思想很简单,就两句话。

3、Redux的架构约束

4、Redux的工作流

862C87CE-6ADA-45CF-BDC6-B84F328D8378.png

5、Redux的简单Demo

// state只读
const defaultState = 0;
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'ADD':
      return state + action.payload;
    default: 
      return state;
  }
};
import { createStore } from 'redux';
var store = createStore(reducer)
store.getState()
// 注册
let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
);

// 销毁
unsubscribe();
const action = {
  type: 'ADD',
  payload: 'Learn Redux'
};

store.dispatch(action);

5、Redux让开发者专注于数据流的处理。

Redux框架约束Store,封装了 订阅store.subscribe分发store.dispatch 的行为;封装了Action的动作;抽象定义了State对象。框架定义一整套完整的工作流程,开发者只需要关注于React组件页面,专注于相关业务数据流的设计和处理。

框架提供以下方式支持数据多样性。
const initialState={
    a: data 1,
    b: data 2,
    c: data 3
}

我们可以把 Reducer 函数拆分,不同的函数负责处理不同属性,最终把它们合并成一个大的 Reducer 即可。Redux 提供了一个 combineReducers 方法,用于 Reducer 的拆分。你只要定义各个子 Reducer 函数,然后用这个方法,将它们合成一个大的 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)
  }
}

四、中间件技术,让Redux支持异步

Redux从生成action,dispatch action,生成新的state,页面更新,这一工作流是同步的。
实际开发中,需要异步的场景,redux如何支持呢? 这需要用到中间件技术。

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  reducer,
  applyMiddleware(thunk)
);

Redux参考

阮一峰:Redux 入门教程(一):基本用法
阮一峰:Redux 入门教程(二):中间件与异步操作
Redux入门教程(快速上手)
Redux教程

上一篇 下一篇

猜你喜欢

热点阅读