一、概念: http://caibaojian.com/react/redux-basic.html 或 https://www.cnblogs.com/maopixin/p/9989236.html 或 https://www.jianshu.com/p/7a867be0594a(推荐)
1、redux 是独立于react的,其他的框架也是可以使用的。
二、安装 redux模块:
npm install --save redux react-redux redux-thunk npm install --save-dev redux-logger
说明: redux 和 react-redux 是必须的 redux-thunk可以帮你实现异步action。redux-logger可以实现监测redux的变化,
Redux
状态管理工具,与React没有任何关系,其他UI框架也可以使用Redux
react-redux
React插件,作用:方便在React项目中使用Redux。(react-redux 和 redux 有版本兼容性的问题。测试有效的版本 redux@4.0.1、react-redux@5.0.7、redux-thunk@2.3.0)
react-thunk
中间件,作用:支持异步action
import { createStore } from 'redux'; import reducers from './reducers.js' // reducers 是一个函数,返回一个最新的 state。调用这个函数时,会传入 两个参数:state和action。其中state指的是原仓库的状态, action指的是新传递的状态 const store = createStore(reducers); // 程序调用dispatch方法,就会触发 reducers 函数,修改state值。 创建时就会调用 reducers 函数。 export default store;
2、创建reducer: 调用 store 的 dispatch方法,就会触发 reducers 函数,修改state值。 创建时就会调用 reducers 函数。
页面调用 dispatch 方法,怎么赋值给 store 的 state,自己可以在 reducers 函数中自由发挥。
const defaultState = { inputValue: 'fine' //默认state数据 } export default (state = defaultState , action)=>{ switch (action.type){ case 'inputValue': state.inputValue = action.value break; default: break; } return state; }
3、组件获得store中的数据 :
this.state = store.getState();
4、组件 改变 store 中的数据(action):
注意:action 必须是一个对象,且有一个 type 字段。
const action = { type:'inputValue', value:'1234567' } setTimeout(() => { store.dispatch(action) },10000)
5、store 数据更新了,需要在 组件的constructor 生命周期中订阅redux的状态 ,才能同步更新。(订阅的API方法 subscribe)
constructor(props){ this.state = store.getState(); store.subscribe(this.change); change是一个函数,当store改变,就会订阅发布,执行 subscribe 内的 函数。在 change 函数里面,在修改本地的 state ,更新视图 }
6、上面知道怎么用,现在 可以看下 redux 的设计原理了: https://www.jianshu.com/p/e984206553c2
1、<Provider> 组件: 能够使 里面的 组件都能 访问到
Redux store
中的数据。【根组件外面包了一层Provider组件,所有子组件就都可以拿到 store
中的数据了。】connect
方法使你可以从Redux store
中读取数据(以及当store更新后,重新读取数据)。如:// 将state映射到Counter组件的props function mapStateToProps(state) { // connect 第一个函数参数会把 store 的 state 作为参数传入,方便这个函数内 获取 state 中 的数据,映射到当前组件的props中。方便组件 通过 props 获取 store的数据。 return { value: state.count } } // 将action映射到Counter组件的props function mapDispatchToProps(dispatch) { // connect 第二个函数参数会把 store 的 dispatch 作为参数传入,方便这个函数内 获取 store的dispatch方法 ,映射到当前组件的props中。方便组件通过props的方法修改 store 的数据。 return { onIncreaseClick: () => dispatch(increaseAction) } } // 传入上面两个函数参数,将Counter组件变为App组件。 Counter组件 拷贝一份,通过 mapStateToProps、mapDispatchToProps函数,给 拷贝的组件传入 props 属性 和方法。【这里是给组件的props传入了 props.value 属性 和 props.onIncreaseClick 方法 】 const App = connect( mapStateToProps, mapDispatchToProps )(Counter)