reactjs - 是否可以在其构造函数签名中安全地解构 ES6 React Component 类?

标签 reactjs ecmascript-6 es6-class

我有一个扩展 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>
  }
}

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

Warning: MyComponent(...): When calling super() in MyComponent, make sure to pass up the same props that your component's constructor was passed.

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

最佳答案

If you look at this line in the React source code ,您会看到它进行浅层检查以查看 props 对象是否匹配。

// 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
);

当你将它传递给 super 时,你创建了一个 props 的克隆,所以它会引发警告。

关于reactjs - 是否可以在其构造函数签名中安全地解构 ES6 React Component 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40478041/

相关文章:

javascript - React onClick 事件触发点击子元素

android - 使用自定义对象在 React native 和 android 之间进行 React native 通信

javascript - 检查构造函数是否继承了 ES6 中的另一个构造函数

javascript - ES6 如何覆盖 toString() 方法?

javascript - 为什么js类不使用public和private关键字?

javascript - 是什么导致我的 React 应用程序中出现警告 "Unexpected Fiber popped"?

reactjs - 使用 React.js 从 JSX 中的 for 循环创建 HTML

javascript - 没有 'let' 或 'var' 的 ES6 类中 undefined variable

javascript - 如何在 react 钩子(Hook)中有一个条件

javascript - 获取类中的所有静态 getter