简体   繁体   English

在 Modern React 中将数据向上传递到组件层次结构

[英]Passing data up the components hierarchy in Modern React

In a react component hierarchy one can pass data from the root component to some component inside component tree by passing props .在 React 组件层次结构中,可以通过传递props将数据从根组件传递到组件树中的某个组件。 But what is the optimum way of passing data up the hierarchy?但是将数据向上传递到层次结构的最佳方式是什么? I can think of passing methods from the wrapper to the child.我可以考虑将方法从包装器传递给孩子。 Is there any better way of handling data flow in a deep nested components scenario?有没有更好的方法来处理深度嵌套组件场景中的数据流?

I don't think there is something wrong with passing callback functions from parent to child component.我不认为将回调函数从父组件传递到子组件有什么问题。

But, in this case:但是,在这种情况下:

<parent onSomeEvent={..}>
  <first-child onSomeEvent={..}>
    <second-child onSomeEvent={..}>

... ...

When need to pass some data from child component to higher level parent, and you don't want to pass the callback function like above example you may use state management like react-redux , MobX .当需要将一些数据从子组件传递给更高级别的父组件,并且您不想像上面的示例那样传递回调函数时,您可以使用诸如react-reduxMobX 之类的状态管理。 You can also use react context api and hooks if you don't want to use additional library.如果你不想使用额外的库,你也可以使用react context api 和 hooks

You just have to keep in mind it isn't overkill for your app.您只需要记住它对您的应用程序来说并不过分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM