React redux store与组件状态

时间:2017-08-14 04:29:09

标签: javascript reactjs

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

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

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

1 个答案:

答案 0 :(得分:0)

这是一种解决问题的方法。该解决方案假定InputFormComponentActionComponentParentComponent范围内,或者可以轻松地包含在其中。{/ p>

ParentComponent包含connect,可以访问redux store。父级在抽象级别上的渲染看起来像这样(可能有任何级别的兄弟姐妹或嵌套):

//Parent Component
render() {
    return (
        <InputFormComponent
            data={this.{state|prop}.initialData}
            userClickedSave={this.state.userClickedSave}
            clickSavedAcknowledged={this.clickedSavedAcknowledged}
        />

        <ActionComponent
            onSaveClicked={this.onSaveClicked}
        />
    )
}

从上面的代码中我们可以理解ParentComponent在其userClickedSave上有一个state标记。它有一个名为onSaveClicked的方法,从ActionComponent调用时会将this.state.userClickedSave更新为true

现在让我们看看InputFormComponent userClickedSavecomponentWillReceiveProps的行为{/ 1}}:

//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,因此当用户单击“保存”按钮时,该过程可以重复。