将参数传递给 mapDispatchToProps() [英] Pass parameters to mapDispatchToProps()

查看:33
本文介绍了将参数传递给 mapDispatchToProps()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能说谎,我对 react-redux 有点困惑.我认为很多操作都需要参数(例如从商店中删除项目),但即使我仍在阅读有关如何以这种方式从组件分派以传递参数的信息,现在大约 2 小时,我也没有得到任何答案.我尝试了 this.props.dispatchmapDispatchToProps,我总是得到 this.props... is not a function 消息.这是我正在尝试做的:

I can't lie, i'm a bit confused about react-redux. I think lot of the actions require parameters (for an example deleting items from the store), but even if i'm still reading about how to dispatch from component in that way to pass a parameter, about 2 hours now, i didn't get any answers. I was tried with this.props.dispatch and with mapDispatchToProps, i always get the this.props... is not a function message. Here's what i'm trying to do:

  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);

这不是我需要用动作调度的唯一地方,动作对象的属性取决于传递给函数的另一个属性,所以我真的很想做,将属性传递给动作的最佳方法是什么,并在 React 组件中调度它.

It isn't the only place where i need to dispatch with an action, where the action's object's properties depending on another property passed to the function, so i really want to do, what's the best way to pass property to action, and dispatch it within a react component.

推荐答案

import { bindActionCreators } from "redux"

function mapDispatchToProps(dispatch) {
    return(bindActionCreators({
        deleteFromArray: (array) => {getTheArray(array)}
    }, dispatch))
}

在你的哑组件中,只需调用例如 this.props.deleteFromArray([1,2,3,4])

In your dumbComponents, just call e.g this.props.deleteFromArray([1,2,3,4])

这应该可以解决问题.你没有绑定调度

This should solve the issue. you are not binding with dispatch

这篇关于将参数传递给 mapDispatchToProps()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆