React---Redux

45 阅读2分钟

Redux

(1)Redux基本认识

我们为什么需要状态管理器Redux?为了方便的组织和管理组件之间的数据。

redux.png

  • Redux是什么? Redux是一个流行的JavaScript框架,为应用程序提供一个可预测的状态容器。Redux基于简化版本的Flux框架,Flux是Facebook开发的一个框架。在标准的MVC框架中,数据可以在UI组件和存储之间双向流动,而Redux严格限制了数据只能在一个方向上流动。

redux-store.png

Store:存储数据的公告区域;eg--图书管理员;

React Component:页面组件;eg--借书的用户;

Reducer:数据存放位置;eg--图书记录本;

Action Creators:动作;eg--结束的时候,跟图书管理员说的话;

  • Redux基本原则

    • 单一数据源;
    • state是只读的;
    • 使用纯函数来执行修改;
  • Redux核心API

    • createStore(reducer):创建数据仓库: import {createStore} from "redux";
    • store.getState():用于获取store里面的数据;
    • store.dispatch(action):用于派发action,触发reducer,执行修改动作;
    • store.subscribe(componentMethods):订阅store的修改,只要store发生改变,组件中的回调函数就会被执行;

(2)store的创建和使用

  • 使用Redux需要安装该模块

    cnpm i redux –save
    
  • 创建reducer(store/reducer.js),提供数据源,是一个纯函数

    // src/store/reducer.js
    const defaultState = {
        username: "小明",
        stulist: ['a', 'b', 'c']
    }
    

//1、state用于提供为仓库提供数据源,需要给定一个初始值 //2、action用于对state 进行更新处理,表示要执行的动作,通过dispatch(action)触发;action被传递到reducer内部来处理,action中必须有一个type字段

const reducer = (state=defaultState) => { //action…… return state;//必须返回处理后的state }

export default reducer;

​
- 创建数据仓库(store/index.js):createStore()
​
  ```react
  // src/store/index.js
  import {createStore} from "redux";
  import reducer from "./reducer";
​
  const store = createStore(reducer);
  export default store;
  • 组件内部使用数据:getState()

    //组件内部引入仓库
    import store from "./store/index";
    ​
    //获取数据
    <h2>{store.getState().username}</h2>
    

(3)数据的修改和订阅

  • 在组件内部定义要执行的动作action,并触发该动作dispatch。action中type字段是必须的,值通常大写:

    addValue() {
        const action = {
                type: "ADD",
                data: "测试数据"
        }
        store.dispatch(action);
    }
    
  • 接收动作并修改数据:通过dispatch触发动作后,会将action传递到reducer函数的第二个参数中

    const reducer = (state=defaultState, action) => {
        switch(action.type) {
            case "ADD": 
                state.stulist.push(action.data);
                break;
            default: 
                break;
        }
        return state;
    }
    
  • 组件中及时响应更新的数据:订阅

    componentDidMount() {
        // 订阅store改变事件
        store.subscribe(this.changeValue.bind(this));
    }
    changeValue() {
        this.setState(store.getState())
    }
    

    subscribe函数可以监听Redux中state的变化,一旦Redux中的state发生了变化,render函数就会被调用,页面就会被重新渲染