gpt4 book ai didi

javascript - 我可以手动将调度添加到组件的 props 而不是 connect() 吗?

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

经过几个小时的研究,我得到了一个问题,为什么我的组件没有得到this.props.dispatch。上一个问题:Pass parameters to mapDispatchToProps() 。所以我找到了问题的根源,但不知道如何解决。我有由递归函数创建的嵌套组件。例如:

//App.js render
<Provider>
</ExampleComponent counter = {6}>
</Provider>

//ExampleComponent.js

createChild = () => {
const childs = [];
for (let i = 0; i < this.props.counter; i++){
childs.push(</ExampleComponent counter = {this.props.counter - 1}>)
}
return childs
}

render(){
return this.createChild()
}

export default connect()(ExampleComponent)

这里的问题是,只有 Provider 的直接组件接收 dispatch 作为属性,即使所有组件都是相同的,并且在理想情况下也是如此方式,它们应该连接起来。这是一张图片,以便更好地理解: enter image description here

那么最好的解决方案是什么?我如何连接所有组件? (只有我个人的想法是手动添加调度作为组件的 Prop ,每个解决方案都很好地解决了问题)(并且我需要告诉我使用react-beautiful-dnd,它也使用redux,所以它可能会冲突我的商店。我不知道,可能是。)

最佳答案

connect 需要 2 个参数,第一个用于状态,第二个用于调度。

您收到此错误的原因是您忽略了 props。

const mapStateToProps = (state, ownProps) => {
// state has access to your store
// ownProps has access to the props you are passing.
return {
...ownProps,
};
};

const mapDispatchToProps = (dispatch) => {
return {
dispatch: (action) => dispatch(action),
};
};

export default connect(mapStateToProps, mapDispatchToProps)(ExampleComponent);

您还可以在此处导入您的操作,并创建使用 redux 中的绑定(bind)操作创建器分派(dispatch)您的操作的函数,但我认为没有必要。

关于javascript - 我可以手动将调度添加到组件的 props 而不是 connect() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670980/

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