繁体   English   中英

React Redux存储与组件状态

[英]React redux store vs component state

我有一个带有输入元素的组件。 Onchange,我想更新Redux存储和本地状态,因为我在组件中渲染了{this.state.inputValue}。

我需要将其保存在Redux存储区中的原因是,用户可以随时点击保存按钮(位于不同组件上)。

我想不出任何其他方式来保持本地状态,并允许“保存”访问数据。 但似乎这种方法打破了“单一事实来源”规则。 什么是正确的方法? 谢谢。

这是解决问题的一种方法。 该解决方案假定InputFormComponentActionComponent在某些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}
        />
    )
}

从上面的代码中,我们可以了解到ParentComponentstate上有一个userClickedSave标志。 它有一个叫做方法onSaveClicked从调用时ActionComponent将更新this.state.userClickedSavetrue

现在让我们看一下InputFormComponent在其componentWillReceiveProps上对userClickedSave表现:

//Input form component
componentWillReceiveProps(nextProps) {
    if (nextProps.userClickedSave && this.props.userClickedSave !== nextProps.userClickedSave) {
        nextProps.clickSavedAcknowledged(this.state.inputValue)
    }
}

InputFormComponent将侦听userClickedSave更改和正确的方案,它将使用当前输入值调用clickSavedAcknowledgedParentComponent现在可以将其保存到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM