将参数传递给mapDispatchToProps()

Ger*_*áth 9 reactjs redux react-redux

我不能撒谎,我对react-redux有点困惑。我认为很多动作都需要参数(例如,从商店中删除商品的示例),但是即使我仍在阅读如何通过这种方式从组件进行分派以传递参数,现在大约2个小时,我没有得到任何答案。我尝试过this.props.dispatch和一起使用mapDispatchToProps,我总是能收到this.props... is not a function消息。这是我想做的事情:

  const getTheArray = (array) => {
    return {
      type: 'GET_ARRAY',
      array
    }
  }
    
    class Example extends......
    
    componentDidUpdate(){
    //i have a button, and when it clicked, turns the status: 'deleted'
        if (this.state.status === 'deleted'){
            fetch('http://localhost:3001/deleteitem', {
                method: 'post',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    id: this.props.id
                })
            })
            .then(res => res.json())
            .then(data => this.props.deleteFromArray(data))
            .catch(err => console.log(err)) 
        }
    }




function mapStateToProps(state) {
    return {
        array: state.array
    };
}
function mapDispatchToProps(dispatch) {
    return({
        deleteFromArray: (array) => {dispatch(getTheArray(array))}
    })
}
  
export default connect(mapStateToProps, mapDispatchToProps)(Example);
Run Code Online (Sandbox Code Playgroud)

这不是我需要通过操作分派的唯一地方,该操作的对象的属性取决于传递给该函数的另一个属性,所以我真的很想做,将属性传递给操作并分派的最佳方法是什么在反应组件中。

sim*_*lor 2

import { bindActionCreators } from "redux"

function mapDispatchToProps(dispatch) {
    return(bindActionCreators({
        deleteFromArray: (array) => {getTheArray(array)}
    }, dispatch))
}
Run Code Online (Sandbox Code Playgroud)

在你的 dumbComponents 中,只需调用 this.props.deleteFromArray([1,2,3,4])

这应该可以解决问题。您不受调度约束