[英]React-Redux state in the component differs from the state in the store
[英]React redux store vs component state
我有一個帶有輸入元素的組件。 Onchange,我想更新Redux存儲和本地狀態,因為我在組件中渲染了{this.state.inputValue}。
我需要將其保存在Redux存儲區中的原因是,用戶可以隨時點擊保存按鈕(位於不同組件上)。
我想不出任何其他方式來保持本地狀態,並允許“保存”訪問數據。 但似乎這種方法打破了“單一事實來源”規則。 什么是正確的方法? 謝謝。
這是解決問題的一種方法。 該解決方案假定InputFormComponent
和ActionComponent
在某些ParentComponent
或者可以很容易地包裝為一個。
ParentComponent
包含connect
並可以訪問redux存儲。 父級的渲染在抽象級別上看起來像這樣(可以有任何級別的同級或嵌套):
//Parent Component
render() {
return (
<InputFormComponent
data={this.{state|prop}.initialData}
userClickedSave={this.state.userClickedSave}
clickSavedAcknowledged={this.clickedSavedAcknowledged}
/>
<ActionComponent
onSaveClicked={this.onSaveClicked}
/>
)
}
從上面的代碼中,我們可以了解到ParentComponent
的state
上有一個userClickedSave
標志。 它有一個叫做方法onSaveClicked
從調用時ActionComponent
將更新this.state.userClickedSave
至true
。
現在讓我們看一下InputFormComponent
在其componentWillReceiveProps
上對userClickedSave
表現:
//Input form component
componentWillReceiveProps(nextProps) {
if (nextProps.userClickedSave && this.props.userClickedSave !== nextProps.userClickedSave) {
nextProps.clickSavedAcknowledged(this.state.inputValue)
}
}
InputFormComponent
將偵聽userClickedSave
更改和正確的方案,它將使用當前輸入值調用clickSavedAcknowledged
, ParentComponent
現在可以將其保存到redux存儲中:
//Parent component
clickSavedAcknowledged(inputValue) {
this.props.saveInputValue(inputValue)
this.setState({
userClickedSave: false
})
}
onSaveClicked() {
this.setState({
userClickedSave: true
})
}
如您所見, Parent
將數據保存到redux存儲,還將userClickedSave
重新設置為false
,因此當用戶單擊保存按鈕時,該過程可以重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.