在react中组件与组件之间的通讯很麻烦,因而借用redux进行第三方的通讯,经过把数据存储在store里,实现各个组件间快速通讯
1. 核心react
2. 三大原则git
3. 主要组件github
actionnpm
经过dispatch传递数据到store
reducerredux
描述如何响应action更新state
store函数
维持应用的 state;
提供 getState() 方法获取 state;
提供 dispatch(action) 方法更新 state;
经过 subscribe(listener) 注册监听器;
经过 subscribe(listener) 返回的函数注销监听器。
npm install redux --S
详情请移步个人githubthis
1. 建立 store spa
// store/index.js import {createStore} from 'redux'; import reducer from './reducer'; const store = createStore( reducer, ); export default store;
2. 建立 reducercode
// store/reducer.js // 初始 state const initState={ inputValue:'', list:[] }; // reducer能够接收state,可是毫不能修改state,返回的是新的state export 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
// store/reducer.js 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. 监听 state 的变化
constructor(props){ super(props); this.state = store.getState(); //监听store里面的变化,只要store里面的数据发生改变,则当即执行subscribe函数里的函数 store.subscribe(this.handleStoreChange) } StoreChange=()=>{ this.setState(store.getState()); // 感知store发生变化以后,从store里获取最新的数据,而后进行设置 };