我可以在 if 语句中以某种方式使用解构吗?

Can I use destructuring somehow inside an if statement?

有没有办法让我做这样的事情?

if({color, size, shape} = this.props){
  console.log('Received all props!');
} else {
  console.log('There are some missing props');
}

我想知道我是否通过组件的道具收到了所有需要的数据, 如果没有,则抛出错误。

它用于创建可重用的组件。

您可以使用默认值:

function missing(prop) {
    throw new TypeError(`there is a missing ${prop} property`);
}

…
try {
  const {
    color = missing("color"),
    size = missing("size"),
    shape = missing("shape"),
  } = this.props;
  // use color, size, shape here
  console.log("Received all props!");
} catch(err) {
  console.log(err.message);
}

要使用 if 语句,不,您不能使用解构来生成是否所有属性都存在的布尔值。宁愿做一些平常的事

if ("color" in this.props && "size" in this.props && "shape" in this.props) {
  console.log('Received all props!');
} else {
  console.log('There are some missing props');
}

(或者更好的是,检查您期望的值的类型)