gpt4 book ai didi

reactjs - 将参数传递给mapDispatchToProps()

转载 作者:行者123 更新时间:2023-12-03 13:20:42 25 4
gpt4 key购买 nike

我不能撒谎,我对react-redux有点困惑。我认为很多操作都需要参数(例如从商店中删除项目),但即使我仍在阅读如何以这种方式从组件分派(dispatch)来传递参数,现在大约 2 小时,我没有得到任何答案。我尝试使用 this.props.dispatchmapDispatchToProps,我总是收到 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);

这不是我需要分派(dispatch)操作的唯一地方,其中操作的对象属性取决于传递给函数的另一个属性,所以我真的想做,将属性传递给操作的最佳方法是什么,并在 React 组件中分派(dispatch)它。

最佳答案

import { bindActionCreators } from "redux"

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

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

这应该可以解决问题。您没有与调度绑定(bind)

关于reactjs - 将参数传递给mapDispatchToProps(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50669171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com