![](/img/trans.png)
[英]react + redux. can i dispatch an action that will take a component and have another component render it via this.props.children?
[英]Can i add dispatch manually to component's props instead of connect()?
因此,經過幾個小時的研究,我遇到了一個問題,為什么我的組件沒有得到this.props.dispatch
。 上一個問題:將參數傳遞給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
作為屬性接收,並且以理想的方式應該將它們連接起來。 這是一張更好理解的圖片:
那么什么是最好的解決方案? 如何連接所有組件? (僅我個人的想法是手動將分派作為組件的道具添加,每個解決方案都很好地解決了問題)(並且我需要告訴我我使用了react-beautiful-dnd,它也使用了redux,因此可能會發生沖突在我的商店中。我不知道,可能是。)
connect需要2個參數,第一個用於狀態,第二個用於調度。
您收到此錯誤的原因是您忽略了道具。
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的綁定操作創建器創建可調度您的操作的函數,但我認為這不是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.