一、流程 1、当组件修改数据的时候需要调用store.dispatch传递一个action给store 2、store接受到这个action会将action传递给reducers 3、reducer接受到这个actions后做业务逻辑处理。并返回一个新的newState给store,store这个时候就拥有了state 4、下一次数据再次发生改变的时候就不会使用defaultState 而是用store里面的state 5、需要注意的是 reducers里面必须返回一个纯函数 另外reducers里面的state只允许读不允许修改 6、组件如何监听数据的改变 store.subscribe();监听安装:二、步骤yarn add redux --save-dev1.创建store,对比flux,不需要合并空对象import {createStore, combineReducers} from "redux";import numReducers from "../store/combineReducers/numReducers"import todoReducers from "../store/combineReducers/todoReducers"const reducers = combineReducers({ numReducers, todoReducers})const store = createStore(reducers);export default store;2.再在store中创建一个reducers.jsreducers必须有一个默认的statereducers必须返回一个纯函数reducers里面的state只允许读,不允许修改,如果修改的话页面是不会发生改变的import reducers from "./reducers"const defaultState = { inputVal:"", todoList:[]}export default (state = defaultState,action)=>{ switch(action.type){ case "INPUT_CHANGE": //深拷贝 const changeState = JSON.parse(JSON.stringify(state)) changeState.inputVal = action.value return changeState; case "ADD_ITEM": const addItemState = JSON.parse(JSON.stringify(state)) addItemState.todoList.push(addItemState.inputVal) addItemState.inputVal = "" return addItemState; case "DEL_ITEM": const delItemState = JSON.parse(JSON.stringify(state)) delItemState.todoList.splice(action.value,1) return delItemState } return state}3.页面import React,{Component} from "react";import store from "../store"export default class Home extends Component{ constructor(props){ super(props) this.state = store.getState(); //监听 store.subscribe(this.handleUpdate.bind(this)) } render(){ let {inputVal,todoList} = this.state return () } handleChange(e){ let val = e.target.value const action = { type:"INPUT_CHANGE", value:val } store.dispatch(action) } handleAdd(){ const action ={ type:"ADD_ITEM" } store.dispatch(action) } handleDel(params){ const action = { type:"DEL_ITEM", value:params } store.dispatch(action) } handleUpdate(){ this.setState(store.getState()) }}三、通过combineReducers合并多个reducers1.创建combineReducers2.在store>index.js合并import {createStore, combineReducers} from "redux";import numReducers from "../store/combineReducers/numReducers"import todoReducers from "../store/combineReducers/todoReducers"const reducers = combineReducers({ numReducers, todoReducers})const store = createStore(reducers);export default store;3.state后加入reducers名 render(){ //state后加入reducers名 let {inputVal,todoList} = this.state.todoReducers return ({ todoList.map((item,index)=>{ return
- {item}
}) }