【问题标题】:Is the react state meant to be used within the component it is defined?反应状态是否意味着在它定义的组件中使用?
【发布时间】:2018-12-01 16:56:32
【问题描述】:

是否应该在定义它的组件中使用 react 组件状态? 我遇到了一个场景,其中一个组件状态由两个不同的组件更新,并作为一个 prop 传递给它的子组件。但从未在定义它的组件中使用。

例如:我有一个组件 CommonComponent,它有一个状态“stateObj”,它有两个子组件 ChildComponentModifyComponent。 我还有一个组件,CreateComponent,它是 CommonComponent 的父级。

我这里有两种情况:

  1. 在创建动作期间,CommonComponent 接收来自 CreateComponent 的 props 并更新 state- 'stateObj' 并作为 props 传递给 ChildComponent强>

  2. 在修改操作期间,ModifyComponent 使用回调更新 CommonComponent 的状态,进而更新“stateObj” 作为道具传递给 ChildComponent

这是使用组件状态的有效方式吗?据我了解,该状态旨在由定义它的组件使用。但是,这里我没有使用 CommonComponent 中的“stateObj”。但是,我只是用它来向它的子组件发送数据。我是否以正确的方式使用状态?还是有其他方法可以做到这一点?

您的建议真的很宝贵! 提前致谢。

【问题讨论】:

  • 状态不必只在当前组件中。假设我们没有 redux。然后,您必须使用像 reducer 这样的父组件来管理状态并作为道具向下传递。

标签: javascript reactjs react-native state react-props


【解决方案1】:

您可以将状态移动到 CreateComponent 而不是将它放在 CommonComponent 中。所以,ModifyComponent 和 CommonComponent 会有回调 props 来更新 CreateComponent 中的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2017-09-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    相关资源
    最近更新 更多