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

max*_*man 2 ecmascript-6 reactjs es6-class

我有一个扩展的ES6类React.Component,即一个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>
  }
}
Run Code Online (Sandbox Code Playgroud)

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

警告:MyComponent(...):当调用super()时MyComponent,请确保传递组件构造函数传递的相同道具.

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

m0m*_*eni 5

如果你在React源代码中查看这一行,你会看到它进行浅层检查以查看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
);
Run Code Online (Sandbox Code Playgroud)

当你将它传递给super时,你创建了一个道具的克隆,因此它会引发警告.