【问题标题】:Is it possible to safely destructure an ES6 React Component class in its constructor signature?是否可以在其构造函数签名中安全地解构 ES6 React 组件类?
【发布时间】:2017-03-21 13:20:17
【问题描述】:

我有一个扩展 React.Component 的 ES6 类,即一个 React 组件。假设我的组件如下所示:

class MyComponent extends React.Component {
  constructor({ foo, bar, baz, ...props }) {
    super({ foo, bar, baz, ...props });
    this.state = { foo, bar, baz };
  }

  render() {
     return <span>Foo: {this.state.foo} Bar: {this.state.bar} Baz: {this.state.baz}</span>
  }
}

在这里,我在构造函数的签名中使用解构来提取一些我想在组件状态中使用的道具。我确保将这些值传递给 super。但是,当我实际执行类似的代码时,我会看到如下所示的警告:

警告:MyComponent(...):当在 MyComponent 中调用 super() 时,使 确保传递与组件的构造函数相同的道具 通过了。

所以我的问题是,是否可以像我展示的那样在没有相关警告的情况下解构构造函数的签名? (我假设警告的存在是有充分理由的,我同样确信我并不完全理解其中的含义。)

【问题讨论】:

  • 很确定这是因为super 是您必须在函数中调用的第一件事,但如果您使用 babel 进行编译,为了使用解构它必须执行 const foo = props.foo 等。在超级电话之前。你可以做的是super(props),然后在超级调用之后const { foo, bar, baz } = props
  • 我当然知道我可以做到,但这不是我要求的。我上面给出的示例代码实际上确实为我正确绑定了值,但我担心如果以某种方式相同的道具没有通过 super 渗透,则会出现警告。
  • 警告也可能是您正在构建传入对象的克隆。我认为警告是对原始道具的浅层相等检查(因为深的会太贵),所以当你传递正确的东西时,你仍然会收到警告。很确定你在做什么很好,但我写这篇文章的原因是因为我懒得去查看 github 上的 React 源代码:p
  • 谢谢@AR7,这对我来说很有意义。如果您想输入它,我很乐意接受它作为答案。

标签: reactjs ecmascript-6 es6-class


【解决方案1】:

If you look at this line in the React source code,你会看到它做了一个浅层检查来查看道具对象是否匹配。

// other stuff

var propsMutated = inst.props !== publicProps;

// other stuff

warning(
  inst.props === undefined || !propsMutated,
  '%s(...): When calling super() in `%s`, make sure to pass ' +
  'up the same props that your component\'s constructor was passed.',
  componentName, componentName
);

您在将 props 传递给 super 时创建了一个副本,因此它会引发警告。

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2017-06-28
    • 2015-12-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    相关资源
    最近更新 更多