react-redux基本使用

1.创建redux文件夹,新建store文件

2.引入redux 调用createStore()创建一个store

3.因为store只接收一个reducer,如果有多个reducer需要通过combineReducer()方法将多个reducer合并

4.在App主文件中引入react-redux中的Provider并且包裹<Provider store={store}>

5.单独创建对应的reducer文件,文件中创建相对应的reducer纯函数,传入prevState和action两个参数,通过switch case 来返回相对应的newState.

6.来到需要redux管理的页面,从react-redux中导入connect 高阶组件并将组件包裹,connect接收两个参数mapStateToProps和mapDispatchToProps

connect(mapStateToProps,mapDispathcToProps)(xxxxx) mapStateToProps(dispatch,ownProps) : dispatchProps 这个函数的第一个参数就是 Redux 的 store,我们从中摘取了 count 属性。你不必将 state 中的数据原封不动地传入组件,可以根据 state 中的数据,动态地输出组件需要的(最小)属性。

函数的第二个参数 ownProps,是组件自己的 props。有的时候,ownProps 也会对其产生影响。

当 state 变化,或者 ownProps 变化的时候,mapStateToProps 都会被调用,计算出一个新的 stateProps,(在与 ownProps merge 后)更新给组件。

mapDispatchToProps,它的功能是,将 action 作为 props 绑定到组件上,也会成为 MyComp 的 props。 作者:world_7735
链接:https://www.jianshu.com/p/4af924709b35  
上一篇:redux 学习三


下一篇:react withRouter和connect 同时使用的案例