如何通过钩子在React组件之间传递状态?

With React classes when you have state in the constructor you could inherit it to the child component directly and from the child to the parent using callbacks. How can you transfer state from parent to child with hooks? Is the only way useReducer or Redux?

评论
  • 九尾狐
    九尾狐 回复

    随钩子的到来,将道具传递给孩子或将信息从孩子传递给父母的概念并未改变。

    挂钩为您提供了一种将生命周期(如功能和状态)与功能组件一起使用的方法。

    您可以参考这篇文章,以获取有关带有钩子的生命周期的更多详细信息:

    ReactJS lifecycle method inside a function Component

    Please refer the react docs with hooks FAQs

  • 诶!爷我赞
    诶!爷我赞 回复

    Perhaps, you should ask yourself why you would like to use inheritance. It seems like for many cases where many developers tend to immediately think about using OOP-style inheritance, React.js might recommend composition instead (see https://reactjs.org/docs/composition-vs-inheritance.html).

    对于功能组件,合成可能是唯一的选择,这意味着您的“父”组件将渲染“子”组件,并通过子道具传递它需要传递的任何状态。

    您的项目是否需要Redux,应该与composition-vs-inheritance问题完全正交。