# 7.react-redux
# 1.理解
一个react插件库
专门用来简化 react 应用中使用 redux
# 2.React-Reduc 将所有组件分为两大类
- UI组件
只负责 UI 的呈现, 不带有任何业务逻辑
通过 props 接收数据 (一半数据和函数)
不使用任何 Redux 的 API
一般保存在 components 文件夹下
- 容器组件
负责管理数据和业务逻辑
使用 Redux 的 API
一般保存在 containers 文件夹下
容器组件一般包装 UI 组件
# 3.相关API
- Provider
import { Provider } from 'react-redux'
// 让所有组件的可以得到 state 数据
<Provider store={store}>
<App />
</Provider>
1
2
3
4
5
6
2
3
4
5
6
- connect()
// 用于包装 UI 组件生成容器组件
// 用于连接 UI组件 和 redux, 主要向 UI组件传递属性
import { connect } from 'react-redux'
export default connect(
mapStateToprops, // 函数类型, 得到的是state数据 可以简写为 state => ({ count: state }),
mapDispatchToProps // 从 actions 得到的方法
)(Counter)
1
2
3
4
5
6
7
2
3
4
5
6
7
- mapStateToprops()
// 将外部的数据(即state对象)转换为UI组件的标签属性
const mapStateToprops = function (state) {
return {
count: state
}
}
1
2
3
4
5
6
2
3
4
5
6
- mapDispatchToProps()
// 将分发action的函数转换为UI组件的标签属性
// 简洁语法可以直接指定为actions对象或包含多个action方法的对象
1
2
2
# 4.使用react-redux
1) 下载依赖包
npm install --save react-redux
1
2) redux/action-types.js
不变
3) redux/actions.js
不变
4) redux/reducers.js
不变
5) components/counter.jsx
发生变化
# 5.问题
- redux 默认是不能进行异步处理的
- 应用中又需要在 redux 中执行异步任务 (ajax, 定时器)