【问题标题】:React redux store vs component stateReact redux 存储与组件状态
【发布时间】:2018-01-21 21:03:06
【问题描述】:

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

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

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

【问题讨论】:

  • 保存按钮组件和输入组件是父子组件还是完全不同的组件?
  • 就我而言,兄弟姐妹。输入可以将其数据绑定到父对象中的一个对象,这是可行的。但同样,仍然感觉不是一个单一的事实来源。但我真的不知道。
  • 如果有帮助,您可以使用context。尽管您可以在父组件上使用 props 做同样的事情。
  • “保存”有什么作用?输入是否需要知道当前“保存”的内容与最后输入的内容之间的区别?是否有任何理由您不能仅根据this.state.input === props.value(其中props.value 源自state.savedValue)推导出它是否已修改,或者您希望实现这一点?

标签: javascript reactjs


【解决方案1】:

这是解决问题的方法。该解决方案假定InputFormComponentActionComponent 在一些ParentComponent 内,或者可以很容易地封装在一个内。

ParentComponentconnect 包裹,并且可以访问 redux 存储。 Parent 在抽象级别上的渲染看起来像这样(可能有任何级别的兄弟姐妹或嵌套):

//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 的变化,对于正确的场景,它将使用当前输入值调用 clickSavedAcknowledgedParentComponent 现在可以将其保存到 redux 存储:

//Parent component
clickSavedAcknowledged(inputValue) {
    this.props.saveInputValue(inputValue)

    this.setState({
        userClickedSave: false
    })
}

onSaveClicked() {
    this.setState({
        userClickedSave: true
    })
}

如您所见,Parent 将数据保存到 redux 存储并将userClickedSave 重置回false,因此当用户单击保存按钮时,该过程可以重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-21
    • 2020-05-13
    • 1970-01-01
    • 2020-07-22
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多