javascript/react中点前的问号 [英] Question mark before dot in javascript / react

查看:64
本文介绍了javascript/react中点前的问号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 React 中的 三元运算符是什么.

当我开发 React Native 应用程序时,我遇到了这种被 eslint 作为意外标记覆盖的语法

ESLint:解析错误:意外标记.

事情是这样的:

const routeName = route.state?.routes[route.state.index]?.name ??INITIAL_ROUTE_NAME;

这是什么意思?它最终使用 null 合并运算符,但是我不明白问号在点之前是做什么的.

我知道这是一种正确的语法,因为它是来自 expo 的模板,而且它们非常受欢迎在 react-native 开发社区.

谁能帮我解释一下?

解决方案

这是可选链:MDN

<块引用>

可选的链接运算符 ?.允许读取位于连接对象链深处的属性值,而无需明确验证链中的每个引用是否有效.这 ?.运算符的功能类似于 .链接运算符,除了如果引用为空(空或未定义)时不会导致错误,表达式会短路返回值未定义.与函数调用一起使用时,如果给定的函数不存在,则返回 undefined.

当存在引用可能丢失的可能性时,访问链式属性时,这会导致更短和更简单的表达式.在无法确定需要哪些属性的情况下,它在探索对象的内容时也很有帮助.

I know what ternary operator is in React.

When I'm developing react native app I encounter this kind of syntax that is covered by my eslint as unexpected token

ESLint: Parsing error: Unexpected token .

It goes like this:

const routeName = route.state?.routes[route.state.index]?.name ?? INITIAL_ROUTE_NAME;

What does that mean? It uses null coalescing operator in the end, however I can't understand what does the question mark do before a dot.

I know it is a correct syntax because it is a template from expo and they're very popular in react-native development community.

Can anyone help me explain?

解决方案

That's optional chaining: MDN

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

这篇关于javascript/react中点前的问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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