现在我们如果在react中使用redux,有什么不足之处:
1)不管是哪一个组件中使用仓库,都需要引入,不方便
2)在组件中派发一个action时,需要引入store,还需要引入action
理想情况下:
1)把store在根组件中提供 所有的子组件都可以使用之
2)如果把仓库中的状态映射成组件的属性 this.props.xxx
3)如果把派发动作的操作映射成组件的方法
下面介绍一下react-redux:
介绍:这是一个独立的模块,这个模块,可以让我们非常方便的在react中使用redux
安装:npm i react-redux
在react-redux中提供了两个东西:
Provider组件:
可以给所有的组件提供仓库。
connect方法:
可以把方法和状态映射到组件的属性上。
react-redux的使用
1、Provider是一个组件
如何插入一段漂亮的代码片
import React, { Component } from 'react'
import { connect } from "react-redux" //是一个方法
import Add from '../components/Add'
import AsyncAdd from '../components/AsyncAdd'
import Show from '../components/Show'
import Sub from '../components/Sub' //把action creators导进来
import { increment, decrement, incrementAsync } from "../store/action creators/counter"
class Counter extends Component {
render() {
return (
<div> //传给子组件
<Show counter={ this.props.counter }></Show>
<p>
<Add increment={ this.props.increment }></Add>
<Sub decrement={ this.props.decrement }></Sub>
<AsyncAdd incrementAsync={ this.props.incrementAsync }></AsyncAdd>
</p>
</div>
)
}
}
//把映射好的组件导出去
export default connect(state=>( {counter:state.counter} ), {increment, decrement, incrementAsync})(Counter)
// 把仓库中的状态映射成组件的属性 就可以往下传递了
// function mapStateToProps(state) { // state代表仓库中的状态
// return{
// counter:state.counter
// }
// } => state=>( {counter:state.counter}
// function mapDispatchToProps(params) {
// // ....
// }
// 把一个UI组件 转化成 一个智能组件(把仓库中的状态和方法映射到组件中)
// export default connect(mapStateToProps,null)(Counter)
// 第2个参数和可以直接写action creator
// 把仓库中的状态映射成组件的属性,把仓库中的action也映射成组件的属性
先映射到Counter组件上,然后传递给子组件,子组件就可以使用了 通过this.props .xxx进行使用
子组件的使用
import React, { Component } from 'react'
export default class Add extends Component {
render() {
return ( //直接
<button onClick={ e=>this.props.increment() }>加1</button>
)
}
}