[react系列]redux

123 阅读3分钟

redux官网

概念

Redux 是 JavaScript 状态容器,提供可预测化的状态管理。Redux 除了和 React 一起用外,还支持其它界面库。 它体小精悍(只有2kB,包括依赖)

redux流程图

使用场景

"如果你不知道是否需要 Redux,那就是不需要它。"

  • 不需要使用redux
  1. 用户的使用方式非常简单
  2. 用户之间没有协作
  3. 不需要与服务器大量交互,也没有使用 WebSocket
  4. 视图层(View)只从单一来源获取数据
  • 使用redux
    • 多交互,多数据源
      1. 用户的使用方式复杂
      2. 不同身份的用户有不同的使用方式(比如普通用户和管理员)
      3. 多个用户之间可以协作
      4. 与服务器大量交互,或者使用了WebSocket
    • 组件角度使用
      1. 某个组件的状态,需要共享
      2. 某个状态需要在任何地方都可以拿到
      3. 一个组件需要改变全局状态
      4. 一个组件需要改变另一个组件的状态

设计思想

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

redux 使用

  1. 下载redux工具 cnpm i redux -S

  2. 创建store

    const store = createStore(reducer)
    
    store的几个API:
    1.  getState( ):用来获取store中的state;
    2. dispatch( action ):让store中的reducer执行action以用来更新state;
    3. subscrible( listener ):注册监听器;
    
  3. 创建reducer纯函数,为store挂载默认状态 reducer是一个纯函数,是唯一改变数据(副本)的地方。

    import state from "state.js";
    import { INC } from "type.js"
    
    const reducer = function(_state = state,action) {
      let newState = Object.assgin({},state);
      switch (action.type){
        case: INC:
        newState.count++;
          return newState;
        default:
          return _state;
      }
    }
    
  4. 组件使用store的state

// 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()))
  1. 创建actionCreator actionCreator里的方法,作用是执行一些自定逻辑之后,创建一个带有标识性信息的action,交由reducer处理
3个文件
// type.js (const.js)
export const INC = "INC";
export const FUNC = "FUNC"
...

//action.js (只进行action的定义,不dispatch)
import {INC,FUNC} from "type.js"
export const actions = {
  inc(param) {
    return{
      type: INC,
      param,
    }
  },
  func(param) {
    return{
      type: FUNC,
      param,
    }
  }
}
...

// actionCreator.js
import {actions} from "action.js";
import store from "store.js";

export const actionCreator = {
  boundINC(param) {
    let act = actions.inc(param);
    store.dispatch(act);
  },
  boundFUNC(param) {
    let act = actions.func(param);
    stroe.dispatch(act);
  }
}

  1. 在reducer中,根据action上的标识信息做出判断之后,返回一个新状态,这个时候store里的状态已经更改

    type是让reducer识别action的唯一标识

  2. 让组件去获取最新的状态 在组件的初始化阶段的生命周期钩子函数中给store.subscribe传入回调函数,当状态更改的时候这个回调函数就会触发,在这个回调里就可以让组件获取最新的状态之后进行setState,当然,如果发现所用的状态没有更改可以做出判断来决定是否进行setState
我们只需要组件中的事件函数内调用actionCreator中的方法即可。实际上,想要在组件中使用被管理的state,还是要订阅我们通过redux创建的store。
// Component.js
import React from "react";
import store from "store";
import actionCreator from "actionCreator"

class Component extendx React.Component{
  constructor(props) {
    super(props);
    this.state = store.state;
    this.add = this.add.bind(this);
  }
  componentWillMount() {
    sotre.subscribe(()=>{
      this.setState({
        count: store.getState().count
      })
    })
  }
  add() {
    actionCreator.boundINC();
  }
  render() {
    return(
      <div>
        <p>{this.state.count}</p>
        <button onclick={this.add}>inc</button>
      </div>
    )
  }
}