使用redux 目的

在react中组件与组件之间的通信很麻烦,于是借用redux进行第三方的通信,通过把数据存储在store里,实现各个组件间快速通信

redux 基础

1. 核心

  • state:普通对象
  • action:JS 普通对象,用来描述发生了什么,store 数据的唯一来源
  • reducer:把 action 和 state 串起来。接收 state 和 action 作为参数,并返回新的 state 的函数。

2. 三大原则

  • 单一数据源:只存在唯一一个store
  • state只读:唯一改变 state 的方法就是触发 action
  • 使用纯函数进行修改:reducer

3. 主要组件

  • action

    通过dispatch传递数据到store
  • reducer

    描述如何响应action更新state
  • store

    维持应用的 state;
    提供 getState() 方法获取 state;
    提供 dispatch(action) 方法更新 state;
    通过 subscribe(listener) 注册监听器;
    通过 subscribe(listener) 返回的函数注销监听器。

安装redux

npm install redux --S

准备工作

1. 创建 store

// store/index.jsimport {createStore} from 'redux';import reducer from './reducer';const store = createStore(    reducer,);export default store;

2. 创建 reducer

// store/reducer.js// 初始 stateconst initState={    inputValue:'',    list:[]};// reducer可以接收state,但是绝不能修改state,返回的是新的stateexport default (state = initState,action)=>{        return state;}

流程

1. store 的 dispatch(action) 传递 action 给 store,store 会自动转发给 reducer

InputChange = (e) => {    // 告诉store, 输入的类型和输入框中的值    const action = {        // type 属性 必须有        type:'change_input_value',        value: e.target.value,    };    // 把 action 传给 store    store.dispatch(action);    // store 自动传给 reducer};

2. reducer 接收信息,并返回给 store 一个 newState

export default (state = initState,action)=>{    if (action.type==='change_input_value'){        const newState = JSON.parse(JSON.stringify(state)); //简单的深拷贝        newState.inputValue = action.value;        return newState;    }   }

3. TodoList 监听 state 的变化

constructor(props){    super(props);    this.state = store.getState();    //监听store里面的变化,只要store里面的数据发生改变,则立即执行subscribe函数里的函数    store.subscribe(this.handleStoreChange)}StoreChange=()=>{    this.setState(store.getState());    // 感知store发生变化之后,从store里获取最新的数据,然后进行设置};