簡體   English   中英

反應子組件不更新父狀態

[英]React child component not updating parent state

我在應用程序開發中使用React + Electron + Redux 在另一種情況下,我能夠從子組件更新父狀態,但是現在我無法執行此操作,該狀態僅被更新為子組件。

我知道用正確的值調用reducer動作,但是使用錯誤的一個(上一個)重新渲染父組件 ,而使用正確的值僅渲染子組件的子樹。

我的方法:

我在父組件容器中創建一個函數(動作處理程序):

class CreateExerciseCanvas extends React.Component {

focusOnSection (section) { /* this is the function that i'm refering to */
   store.dispatch(actions.focusOnSection(section))
}
render() {
   return ( 
        <CreateExerciseCanvas 
        focusOnSection={ this.focusOnSection }
        /> 
        )
}
}
const mapStateToProps = function (store) {
    return {
        focusOnSection: store.exercise.focusOnSection
    }
}
export default connect(mapStateToProps)(CreateExerciseCanvasContainer)

此功能作為道具傳遞給子容器:

<Index focusOnSection={ this.props.focusOnSection }/>

最后,該方法在子視圖中用作onClick處理程序 這不是用redux + react更新父母的正確方法嗎?

您必須將此上下文綁定到構造函數中的focusOnSection函數,否則它將不知道是什么。

嘗試向您的CreateExerciseCanvas添加類似的構造函數:

constructor(props) {
    super(props);
    this.focusOnSection = this.focusOnSection.bind(this);
}

這可能是關於使用ES6類的最煩人的部分。

如果在focusOnSection (section)檢查this.props的值,您將看到它是undefined 這是因為focusOnSection () {}是短語法focusOnSection: function () {}這是結合this的功能,所以沒有更多this.props

一個解決辦法是硬約束this在構造方法的類:

constructor(props) {
    super(props);
    this.focusOnSection = this.focusOnSection.bind(this);
}

另一個將使用諸如focusOnSelection = () => {}類的箭頭函數,該函數不綁定this 后一種解決方案僅在使用babel時有效(請檢查es2015預設)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM