React-记connect的几种写法

第一种

  最普通,最常见,delllee和官网第写法。

import React, { Component } from 'react';
import {connect} from 'react-redux';
import { Button } from 'antd-mobile';
import { addGunAction , removeGunAction , removeGunAsync}from './store/actionCreators'
class App extends Component {
  render() {
    console.log();
    return (
      <div className="App">
        <p>{this.props.gun}</p>
        <Button type="ghost" size="small" inline onClick={this.props.handeladd}>+</Button>
        <Button type="ghost" size="small" inline onClick={this.props.handeljian}>-</Button>
        <Button type="ghost" size="small" inline onClick={this.props.handelmanjian}>慢-</Button>
      </div>
    );
  }
}
const mapStateToProps=(state)=>({
    gun:state.gun
})
const mapDispachToProps=(dispatch)=>({
    handeladd(){
      dispatch(addGunAction())
    },
    handeljian(){
      dispatch(removeGunAction())
    },
    handelmanjian(){
      dispatch(removeGunAsync())
    }
})
export default connect(mapStateToProps,mapDispachToProps)(App);

第二种

  初次接触,感觉有点绕,不太好理解,为什么点击了,直接就派发action了?

import React, { Component } from 'react';
import {connect} from 'react-redux';
import { Button } from 'antd-mobile';
import { addGunAction , removeGunAction , removeGunAsync}from './store/actionCreators'
class App extends Component {
  render() {
    console.log();
    return (
      <div className="App">
        <p>{this.props.gun}</p>
        {/*⚠️不用像第一种那样,点击调用一个方法,方法里再派发action
        这种直接点击派发action就可以*/}
        <Button type="ghost" size="small" inline onClick={this.props.addGunAction}>+</Button>
        <Button type="ghost" size="small" inline onClick={this.props.removeGunAction}>-</Button>
        <Button type="ghost" size="small" inline onClick={this.props.removeGunAsync}>慢-</Button>
      </div>
    );
  }
}
const mapStateToProps=(state,ownProps)=>({
    gun:state.gun
})
//⚠️这些action已经自动有了dispatch的功能
const actionCreators={ addGunAction , removeGunAction , removeGunAsync}
export default connect(mapStateToProps,actionCreators)(App);

 

转载于:https://www.cnblogs.com/superlizhao/p/9549248.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值