我可以在if语句中以某种方式使用解构吗? [英] Can I use destructuring somehow inside an if statement?

查看:117
本文介绍了我可以在if语句中以某种方式使用解构吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以做这样的事情?

is there a way I could do something like this ?

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

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

I want to know if I received all needed data through my Component's props, and if not then throw an error.

这是用于创建可重用组件。

It's for creating reusable components.

推荐答案

你可以使用默认值:

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

使用如果语句,你不能使用解构来产生一个布尔值是否所有属性都存在。而是做一些通常的事情

To use an if statement, no you cannot use destructuring to produce a boolean whether all properties are there. Rather do something usual as

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');
}

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

(or better yet, check for the type of the value that you expected)

这篇关于我可以在if语句中以某种方式使用解构吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆