反应状态是否打算在它定义的组件中使用?
Is the react state meant to be used within the component it is defined?
React 组件状态应该在定义它的组件中使用吗?
我遇到了一个场景,其中一个组件状态由两个不同的组件更新,并作为道具传递给它的 child。但从未在定义它的组件中使用。
例如:我有一个组件 CommonComponent,它有一个状态 'stateObj' 并且它有两个 child 组件 ChildComponent 和 ModifyComponent。
我还有一个组件,CreateComponent,它是 CommonComponent.
的 parent
我这里有两个案例:
在创建操作期间,CommonComponent 从 CreateComponent 接收道具并更新状态 - 'stateObj' 和作为道具传递给 ChildComponent
在修改操作期间,ModifyComponent 使用回调更新 CommonComponent 的状态,然后 'stateObj'
作为道具传递给 ChildComponent
这是使用组件状态的有效方式吗?据我了解,该状态旨在由定义它的组件使用。但是,这里我没有使用 CommonComponent 中的 'stateObj'。但是,我只是用它向它的 child 组件发送数据。我是否以正确的方式使用状态?或者还有其他方法吗?
您的建议真的很宝贵!
提前致谢。
您可以将状态移至 CreateComponent 而不是将其置于 CommonComponent 中。因此,ModifyComponent 和 CommonComponent 将具有回调道具,这些道具将更新 CreateComponent 中的状态。
React 组件状态应该在定义它的组件中使用吗? 我遇到了一个场景,其中一个组件状态由两个不同的组件更新,并作为道具传递给它的 child。但从未在定义它的组件中使用。
例如:我有一个组件 CommonComponent,它有一个状态 'stateObj' 并且它有两个 child 组件 ChildComponent 和 ModifyComponent。 我还有一个组件,CreateComponent,它是 CommonComponent.
的 parent我这里有两个案例:
在创建操作期间,CommonComponent 从 CreateComponent 接收道具并更新状态 - 'stateObj' 和作为道具传递给 ChildComponent
在修改操作期间,ModifyComponent 使用回调更新 CommonComponent 的状态,然后 'stateObj' 作为道具传递给 ChildComponent
这是使用组件状态的有效方式吗?据我了解,该状态旨在由定义它的组件使用。但是,这里我没有使用 CommonComponent 中的 'stateObj'。但是,我只是用它向它的 child 组件发送数据。我是否以正确的方式使用状态?或者还有其他方法吗?
您的建议真的很宝贵! 提前致谢。
您可以将状态移至 CreateComponent 而不是将其置于 CommonComponent 中。因此,ModifyComponent 和 CommonComponent 将具有回调道具,这些道具将更新 CreateComponent 中的状态。