![](/img/trans.png)
[英]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.