gpt4 book ai didi

reactjs - react : Passing child state to parent state

转载 作者:行者123 更新时间:2023-12-03 13:22:33 24 4
gpt4 key购买 nike

我使用 React 工作一年多了,我读过 Thinking in react , Lifting state up ,和State and lifecycle .

我了解到React的数据流概​​念是单向数据流

来自这些页面的引用:

React’s one-way data flow (also called one-way binding) keeps everything modular and fast.

Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. This is often the most challenging part for newcomers to understand, so follow these steps to figure it out:...

If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.

据我了解,以下示例是不允许的,因为我将子状态数据传递给父级。但我看到一些开发人员这样做:

class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { fromParent: null };
}

addSomething(stateValueFromChild) {
this.setState({fromParent: stateValueFromChild});
}

render() {
return <Child
addSomething={(stateValueFromChild) => this.addSomething(stateValueFromChild)}>
// ...
</Child>;
}
}

class Child extends React.Component {
constructor(props) {
super(props);
this.state = { fromChild: 'foo' };
}

render() {
return <Form onSubmit={() => this.props.addSomething(this.state.fromChild)}>
// ...
</Form>;
}
}

我现在的问题是:

  • 这真的不允许吗?
  • 为什么它不应该是模块化且快速的?
  • 这真的会破坏单向数据流,变成双向数据流吗?
  • 这种方式还会出现哪些其他问题?
  • 当我将状态提升时,您将如何解决以下情况; 50 个使用该子组件的具体父组件,每个父组件是否应该为他们正在使用的同一个子组件拥有相同的初始化子状态?

最佳答案

Is this really not allowed? Why should this not be modular and fast?

非常好的问题。这是允许的。让它正常工作有点棘手,因为这里有状态同步。在现代前端世界中,状态同步被认为是一项非常具有挑战性的任务。

当您需要在两个方向上同步状态时,就会出现此问题。例如,如果此子表单用于编辑列表的某些元素,并且您要更改列表的当前元素。您需要子组件来检测这种情况,并在特定的 UI 更新期间将其本地状态与 props 中的新元素同步。只要你没有这个,就没有问题。

Is this really braking the one-way-dataflow, becoming a two way dataflow?

不,不是。它仍然是单向数据流,因为 React 在设计上无法以任何其他方式工作; UI 更新总是从上到下进行。在您的示例中,您的子级触发一个事件,导致父级更新其状态(完全没问题),这将导致父级和子级的 UI 更新。如果您确实违反了“单向数据流”,您就会感觉到。你会得到一个无限循环或类似的东西。

When i would lift the state up, how would you solve following case; 50 concrete parents that uses that child component, should every parent have a same initialized sub-state for the same child that they are using?

是的,这就是他们所说的“解除国家”的意思。您将根状态组织为反射(reflect)子级状态的树,然后将状态元素以及回调传递给子级以修改根状态。

关于reactjs - react : Passing child state to parent state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com