我不能撒谎,我对 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);
这不是我需要使用操作进行分派的唯一地方,其中操作的对象属性取决于传递给函数的另一个属性,所以我真的想做,将属性传递给操作并分派它的最佳方法是什么在反应组件内。
import { bindActionCreators } from "redux"
function mapDispatchToProps(dispatch) {
return(bindActionCreators({
deleteFromArray: (array) => {getTheArray(array)}
}, dispatch))
}
在你的 dumbComponents 中,只需调用 this.props.deleteFromArray([1,2,3,4])
这应该可以解决问题。您不受调度约束
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)