是否可以在其构造函数签名中安全地解构 ES6 React 组件 class?
Is it possible to safely destructure an ES6 React Component class in its constructor signature?
我有一个扩展 React.Component
的 ES6 class,即一个 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。但是,当我实际执行类似的代码时,我会看到如下所示的警告:
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 时创建了道具的克隆,因此它引发了警告。
我有一个扩展 React.Component
的 ES6 class,即一个 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。但是,当我实际执行类似的代码时,我会看到如下所示的警告:
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 时创建了道具的克隆,因此它引发了警告。