反应如何破坏构造函数中的深层道具?
React How to destruct deep props in constructor?
我的 class 组件中有以下构造函数:
constructor(props) {
super(props);
this.state = {
dirty: this.props.form.dirty // error happens here!
};
}
eslint
returns道具破坏错误。这么深的道具怎么可能?
这本身不是错误。但是你可以使用这样的东西来避免警告。
const { dirty } = props.form;
this.state = { dirty };
或
const { form: { dirty } } = props;
this.state = { dirty };
首先,不要在构造函数中使用 this.props
,因为您会将 props
作为参数。
其次对于解构,你可以这样做:
const {form: {dirty = 'any initial value in case of undefined'}} = props;
this.setState = {
dirty
}
我的 class 组件中有以下构造函数:
constructor(props) {
super(props);
this.state = {
dirty: this.props.form.dirty // error happens here!
};
}
eslint
returns道具破坏错误。这么深的道具怎么可能?
这本身不是错误。但是你可以使用这样的东西来避免警告。
const { dirty } = props.form;
this.state = { dirty };
或
const { form: { dirty } } = props;
this.state = { dirty };
首先,不要在构造函数中使用 this.props
,因为您会将 props
作为参数。
其次对于解构,你可以这样做:
const {form: {dirty = 'any initial value in case of undefined'}} = props;
this.setState = {
dirty
}