gpt4 book ai didi

javascript - React 中的 Constructor(props) 和 super(props) VS constructor() 和 super()

转载 作者:数据小太阳 更新时间:2023-10-29 04:48:56 27 4
gpt4 key购买 nike

我知道这个问题被问过很多次了,但还是不清楚。很多人只是说:

Pass props to constructor if you want to access this.props there

one more example of the answer

官方文档说 Class components should always call the base constructor with props. , 但如果我们不将 props 传递给 constructor ,除了构造函数之外,我们仍然会在任何地方都有 this.props

同样来自 react source code我们可以看到 React.Component 的源代码函数 ReactComponent(props, context) {
this.props = Prop ;
this.context = 上下文;
}

但这让我更加困惑。super() 应该使用两个参数调用:propscontext 。但是我们调用了我们的 super 空并且仍然可以访问两个 this.props。根据 ECMA 文档 super() 调用父级 constructor() 并将参数传递给 super() 。但是我们的 super() 是空的。

所以我的问题是:

  1. 为什么官方文档说:

Class components should always call the base constructor with props.

  1. 如果 super()constructor() 为空,React 如何将 props 设置为子组件?
  2. 无需将 props 传递给 super()constructor() 即可在子组件中访问 props 是否是 React 功能的错误?

最佳答案

这是 Dan Abramov 的回答:

But if we do not pass props to constructor, we will still have this.props everywhere except constructor.

是的,React 在 constructor 运行后无论如何都会设置 this.props。尽管如此,让 this.props 在某些地方工作而不在其他地方工作仍然令人困惑。特别是如果 constructor 和其他方法都调用了一些读取 this.props 的共享方法。因此,为避免任何潜在的混淆,我们建议始终调用 super(props)

Also from source code of Create Element you can see that createElement adds props regardless if you use super(props)

createElement() 与这个问题无关。它创建一个元素,而不是一个实例。

因此,回到您的问题,从技术上讲,只有当您计划在 constructor 或您从 调用的任何方法中访问 this.props 时才有必要构造函数。但是,必须记住这一点非常令人困惑。你可能知道它并且没有调用 super(props),但你团队中的下一个人会想要在 constructor 中访问 this.props > 并且会惊讶于它不起作用。始终指定它以避免这些问题会更容易。

关于javascript - React 中的 Constructor(props) 和 super(props) VS constructor() 和 super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443099/

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