一:优化注意事项
- 容器组件和UI组件整合成一个文件
- 无需自己给容器组件传递state,给包裹一个即可
- 使用了react-redux后也不用再自己检测redux中状态改变了,容器组件可以自动完成这个工作
- mapDispatchToprops也可以简单的写成一个对象
- 一个组件要和redux“打交道”要经过哪几步
1)定义好UI组件—不暴露
2)引入connect生成一个容器组件,并暴露,写法如下
connect(
state => ({key:value}) //映射状态
{ key : xxxxxxAction} //映射操作状态的方法
)(UI组件)
4) 在UI组件中通过this.props.xxxxx读取和操作状态、
二:整合后的组件文件
containers------>Count----->index.jsx
import React, {
Component } from 'react'
// 引入action
import {
createIncreamentAction,createDecreamentAction,createIncrementAsyncAction} from '../../redux/count_action'
// 引入connect用于连接UI组件与redux
import {
connect} from 'react-redux'
// 定义UI组件
class Count extends Component {
state={
carName:'奔驰c63'}
// 加法
increment=()=>{
const {
value}=this.selectNumber
this.props.jia(value*1)
}
// 减法
decrement=()=>{
const {
value}=this.selectNumber
this.props.jian(value*1)
}
// 奇数再加
incrementIfOdd=()=>{
const {
value}=this.selectNumber
if (this.props.count % 2 !== 0) {
this.props.jia(value*1)
}
}
// 异步加
incrementAsync=()=>{
const {
value}=this.selectNumber
this.props.jiaAsync(value*1,1000)
}
render() {
return (
<div>
<h1>当前求和为:{
this.props.count}</h1>
<select ref={
c=>this.selectNumber=c} >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={
this.increment}>+</button>
<button onClick={
this.decrement}>-</button>
<button onClick={
this.incrementIfOdd}>当前求和为奇数再加</button>
<button onClick={
this.incrementAsync}>异步加</button>
</div>
)
}
}
/*
映射状态
*/
// const mapStateToProps=state=>({count:state})
/*
映射操作状态的方法
*/
/* const mapDispatchToProps=dispatch=>({
jia:number=>dispatch(createIncreamentAction(number)),
jian:number=>dispatch(createDecreamentAction(number)),
jiaAsync:(number,time)=>dispatch(createIncrementAsyncAction(number,time))
}) */
// 使用connect()()创建容器组件,让容器组件与UI组件建立联系,并暴露容器组件
export default connect(
state=>({
count:state}),
// mapDispatchToProps的一般写法
/* dispatch=>({
jia:number=>dispatch(createIncreamentAction(number)),
jian:number=>dispatch(createDecreamentAction(number)),
jiaAsync:(number,time)=>dispatch(createIncrementAsyncAction(number,time))
}) */
// mapDispatchToProps的简写(写一个对象)
// 这里虽然表面没有dispatch,但是只要react-redux收到了action就会帮助自动分发,自动dispatch
{
jia:createIncreamentAction,
jian:createDecreamentAction,
jiaAsync:createIncrementAsyncAction
}
)(Count)
优化主要就是在ui组件和容器组件中,redux还是和没优化之前一样,另外src----->index.js中不用我们使用render再次调用render,react-redux自动回刷新更新组件渲染到页面