嗨(:我一直試圖使用一個孩子 - 父母溝通的系統來確保我在孩子中所做的更改顯示在父母中,更具體地說,在我的React應用程序的其中一個頁面中,我想要一些「開關」對象,我希望能夠打開/關閉這些對象,並使這些更改持續存在於不同的頁面中。 :Javascript - 兒童狀態的變化在父母不持久
在我的父母創建一個狀態:
class dashboard extends Component { constructor(props) { super(props); this.updateObject.bind(this); } state = { test_dictionary: {'test': false} };
DEFI ne是父級內的一個函數,用於更新上述狀態。
updateObject(current_key) { var new_state = Object.assign({}, this.state.test_dictionary); new_state[current_key] = !new_state[current_key]; // I want to flip the boolean when clicked this.setState({test_dictionary: new_state}); }
然後,我將狀態和函數(如上所示)從父項傳遞給子項。
<childView test_dictionary={this.state.test_dictionary} updateObject={this.updateObject}/>
最後,當我是孩子裏,我嘗試使用功能,並傳遞到更新每一個時間內交換機對象改變雙親狀態字典中的狀態。
<Switch checked={this.props.test_dictionary['test']} onChange={this.props.updateObject.bind('test')} />
然而,這不是做什麼,我希望它做的事。我嘗試閱讀了許多關於如何設置孩子 - 父母溝通的不同例子,我認爲這很接近它。當我嘗試點擊切換對象我「M得到的錯誤是:
Uncaught TypeError: Cannot read property 'updateObject' of undefined
at String.handleSelectionChange (childView?9911:28)
at String.handleSelectionChange (createPrototypeProxy.js?9d62b87:44)
at Switch.setChecked (Switch.js?bc7e1ee:54)
at toggle (Switch.js?bc7e1ee:105)
at Object.ReactErrorUtils.invokeGuardedCallback (ReactErrorUtils.js?c23a69d:69)
at executeDispatch (EventPluginUtils.js?46a03e1:85)
at Object.executeDispatchesInOrder (EventPluginUtils.js?46a03e1:105)
at executeDispatchesAndRelease (EventPluginHub.js?2c8fe93:43)
at executeDispatchesAndReleaseTopLevel (EventPluginHub.js?2c8fe93:54)
at Array.forEach (<anonymous>)
我將不勝感激任何幫助,您可以提供
非常感謝您的反饋!我改變了你的建議,現在的錯誤是: '未捕獲的TypeError:不能讀取未定義的屬性'test_dictionary'而不是'未捕獲的TypeError:無法讀取未定義的屬性'updateObject'。從這裏,我假設在我的'updateObject'函數中,它不能到達我試圖訪問的'this.state.test_dictionary'?你有任何進一步的建議?我非常感謝你的幫助! –