这个 JavaScript 表达式是什么意思?

What does this JavaScript expression mean?

我正在使用 react-navigation,但我无法理解此语法的含义。

React.useEffect(() => {
    if (route.params?.post) { <<<<<WHAT IS THIS ?
      // Post updated, do something with `route.params.post`
      // For example, send the post to the server
    }
  }, [route.params?.post]);

它是否像 obect.doesPropertyExist.subProperty 或其他东西一样工作?


我已尝试浏览 MDN 文档,但找不到对此类语法的任何参考。我无法在我的节点 REPL 中对随机对象使用类似的语法。

叫做Optional Chaining operator。 shorthand

route.params && route.params.post

它被称为可选链接。 MDN 文档中提供:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

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.

if(route.params.post) 然后做点什么。 它检查 route.params 是否有对象 post