redux:管理项目中的状态
三大原则
- 单一数据源
- state是只读的
- 使用纯函数来修改state (reducer)
重要概念
- state:整个应用的状态
- action:描述如何修改state的对象,并且这个对象必须要有type属性
- reducer:修改state的纯函数,接收旧的state、action,返回新的state
- store:使用action来描述“发生了什么”,和使用reducers来根据action更新state的用法。store就是把它们联系到一起的对象。一个redux应用只能有一个store。
store的方法:
和组件结合
不管在哪里使用redux,都可以使用,两个毫不相干的组件里都可以使用。
使用react-redux的库 该库的作用就是让组件和仓库通信
也就是说通过这个仓库,可以把组件与组件之间关联起来。A组件向B组件发送数据没有问题,B组件向A组件发送数据也没有问题。通过仓库把当前组件全部关联起来。
下载:npm i react-redux -S
Api:
- Provider : 整个项目只需要引入一次 也是一个组件 包裹在整个项目的最外层 参数:store
- connect : 高阶组件 connect(参数是两个函数)(组件) ,在需要仓库的地方使用
使用
App.js文件:
回到需要通信的组件里,ReactRedux.js:
- 引入connect
- 使用connect去包装组件
- 修改仓库状态
- 在组件的props中接收或者处理仓库数据
import React, { Component } from 'react';
import { connect } from 'react-redux' //connect连接
import { Button } from 'antd'
class ReactRedux extends Component {
render() {
let { count, countIncrement, countDecrement } = this.props
//console.log(this.props)
return (
<div>
<Button type='primary' onClick={() => {
countDecrement()
}}>-</Button>
{count}
<Button type='primary' onClick={() => {
countIncrement()
}}>+</Button>
</div>
);
}
}
//参数 state:仓库中的state 从store里拿数据
//返回值:在页面中使用仓库的数据 返回值是一个对象
const mapStateToProps = (state) => {
console.log(state)
return {
count: state
}
}; //可以获取到state
//参数dispatch:分发数据到仓库
//返回值是一个对象
const mapDispatchToProps = dispatch => { // store.dispatch({type:'标识'}) dispatch===store.dispatch true
console.log(dispatch)
return {
// 函数(){
// dispatch()
// }
countIncrement() {
dispatch({ type: 'INCREMENT' });
},
countDecrement() {
dispatch({ type: 'DECREMENT' });
}
}
}; //可以获取到state
//connect(a,b) 返回的是高阶组件
export default connect(mapStateToProps, mapDispatchToProps)(ReactRedux)