React-記connect的幾種寫法

第一種

  最普通,最多見,delllee和官網第寫法。react

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了?redux

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);
相關文章
相關標籤/搜索