nullish凝聚运算符在ecmaScript 2020中发布。
它是适用于两个或多个操作数的逻辑运算符。
什么是nullish凝聚运算符以及如何在react组件中使用它?
你可以查看如何在Angular中使用运算符。
nullish联合运算符是一个逻辑运算符,用于检查两个值是否为空或未定义。
nullish是一个参数的空值和未定义值的缩写,coalescing是指合并两个值。
下面是一个语法
firstexpression ?? secondexpression
双重问号是null联合运算符的一个符号。
这将返回值
- 如果第二个表达式为空或未定义,则返回第一个表达式的值
-
- 如果第一个表达式是空的或未定义的,则返回第二个表达式的值。
下面是一个例子
const output = null ?? 'welcome';
console.log(output); // welcome
const output1 = 121 ?? 0;
console.log(output1); //121
为了检查,我们有两个在typescript和javascript中引入的操作符
- 可选的链式运算符(?)
- 空值凝聚运算符(???)
React可选链式运算符
在react组件中,当你显示状态对象的数据时,你必须使用空值检查
例如,用户对象被存储在状态对象中。使用可选的链式运算符? ,我们将检查用户是否为空
如果用户对象为空或未定义,名称返回未定义。
如果用户对象不是空的或未定义的,user.name将按预期返回。
下面是一个完整的例子
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps { }
interface AppState {
name: string;
user: User;
}
class User{
id:number
name:string;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'React'
};
}
render() {
return (
Welcome {this.state.user?.name}
);
}
}
render(, document.getElementById('root'));
我们已经看到了如何使用可选的链式检查null检查
让我们看看凝聚运算符是如何简化同样的事情的
const name=this.state.user && this.state.user.name;
下面是一个完整的例子
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps { }
interface AppState {
name: string;
user: User;
}
class User{
id:number
name:string;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'React'
};
}
render() {
const name=this.state.user && this.state.user.name;
return (
Welcome {name}
);
}
}
render(, document.getElementById('root'));
这个nullish操作符适用于所有数据类型值的类型描述
- 数字
- 字符串
- 布尔型
- 对象
这在所有最新的react, typescript版本中都支持。
结论
这有助于在编写react组件时写出简洁的代码。