美文网首页
react-redux

react-redux

作者: 城门小胡同 | 来源:发表于2019-04-23 14:36 被阅读0次

react-redux  中文文档   https://www.redux.org.cn/docs/react-redux/api.html

在使用redux 的时候  需要引入  redux  react-redux

npm install --save redux
npm intsall --save react-redux

第一步:

创建 reducer , Reducers 指定了应用状态的变化如何响应 actions 并发送到 store 的 ,
reducer  是用来管理 state,根据不同的action  返回不同的值
应用很大的时候需要拆分 reducer , 最后合并成一个 根reducer
这里就需要用到 combineReducers  函数

单个reducer 合成后的根 rootReducer

最后:把根rootReducer 暴露给 store

第二步:

创建  store   store 来存放所有的 state。应用中仅有一个 store
通过函数 createStore  创建 store ,如果使用中间键,则需要引入 applyMiddleware 函数
最后 : 把store 暴露出去  在index.js  文件总引入 配置全局的 store

创建的 store 文件

第三步:

  在index.js  文件中 引入 store , 配置全局store 还需要 引入 Provider 

index.js

第四步:

创建 action : 

action

这里action  为了方便管理 增加了一个contants 文件夹  把 type  定义进去  再引入过来

contants文件

第五步:

在页面中 引入 connect,  

import { connect } from 'react-redux';

connect  有四个参数

mapStateToProps : 用来更新 state  以便页面中使用

mapDispatchToProps :  可以定义函数 直接 触发action type   如下:

第一种写法 第二种写法 第三种写法

比较这三种写法可以看出 : 

第一种  :
是 通过 mapDispatchToProps  函数  把 increment 方法  放入props中,
在调用时increment   通过mapDispatchToProps 自带的dispatch 直接触发 action  

第二种 : 
直接引入action  中的方法 ,放入connect 中,实现方法放入props里,再通过调用
props中的方法触发action

第三种 : 
引入所有的action ,通过bindActionCreators  函数  把每个action 都增加 dispatch 属性
通过调用props 中的方法 触发action

这是有缓存的时候这么用  一般情况写正常写就可以了  这些不必要加

相关文章

网友评论

      本文标题:react-redux

      本文链接:https://www.haomeiwen.com/subject/xqcdeqtx.html