简体   繁体   English

是否可以将可选链接与数组和映射(在 Javascript 中)结合起来?

[英]Is it possible to combine optional chaining with arrays and map (in Javascript)?

I recently learned about optional chaining in Javascript and have been making use of it in a React/NodeJS project.我最近了解了 Javascript 中的可选链接,并一直在 React/NodeJS 项目中使用它。 Works great.效果很好。

I noticed I have been using it with arrays map , even without thinking about it much -- it seemed a natural use (here items is an array, or possibly undefined )我注意到我一直在将它与数组map一起使用,即使没有考虑太多——这似乎是一种自然的用途(这里的items是一个数组,或者可能是undefined

        {items?.map(postListItem => ....

That is, it will map if items exists, but not if items is undefined , but would avoid any run-time errors if I were to call map on undefined也就是说,如果items存在,它将映射,但如果itemsundefined则不会映射,但如果我要在undefined上调用map ,它将避免任何运行时错误

Nonetheless I don't know if this is an acceptable use or whether I'm mis-using optional chaining.尽管如此,我不知道这是否可以接受,或者我是否误用了可选链接。 I searched for an answer but as of yet haven't been able to find one, which makes me suspect I'm mis-using it.我搜索了一个答案,但到目前为止还没有找到答案,这让我怀疑我误用了它。 Any info much appreciated!非常感谢任何信息!

See answer here regarding the typescript usage.请参阅此处有关打字稿使用的答案。 You need a period for array null safe Optional Chaining.您需要一个用于数组空安全可选链接的句点。

    this.mostRecentMfaAttempt = this.verificationsAttempts?.content?.[0]

How to use optional chaining with array in Typescript? 如何在 Typescript 中使用带有数组的可选链接?

Using optional chaining operator for object property access 使用可选链接运算符进行对象属性访问

If the chaining fails, the expression will evaluate to undefined .如果链接失败,表达式将评估为undefined

When a child is evaluated to undefined , it just won't render .当孩子被评估为undefined时,它不会呈现

Conditional rendering is already quite a common strategy.条件渲染已经是相当普遍的策略。 Previously, when you have something that may be an array or may be undefined , and you want to map if there's an array, you would have had to do something like:以前,当您有可能是数组或undefined的东西时,如果有数组,您想要映射,您将不得不执行以下操作:

{ items && items.map( ...

This works because, if items is undefined , the whole expression will be evaluated to undefined , and no rendering will happen, and no errors will be thrown.这是有效的,因为如果itemsundefined ,整个表达式将被评估为undefined ,并且不会发生渲染,也不会引发错误。

Using optional chaining works exactly the same way, except that it's more concise.使用可选链接的工作方式完全相同,只是它更简洁。 So yes, this is a perfectly valid thing to do.所以,是的,这是一件非常有效的事情。

Optional chaining is stage 4 , so you can count on it working reliably.可选链接是第 4 阶段,因此您可以指望它可靠地工作。

Arrays are objects .数组是对象 But optional chaining isn't only for objects - it can work for anything which may have a property or method.但是可选链不仅仅适用于对象——它可以适用于任何可能具有属性或方法的东西。 Eg const bar = foo?.toFixed(2) will work fine if foo is null , undefined , or a number (numbers have a toFixed method).例如,如果foonullundefined或数字(数字有toFixed方法), const bar = foo?.toFixed(2)就可以正常工作。

The optional chaining way to your problem is:解决问题的可选链接方式是:

{items?.map?.(postListItem => ....)

Read more here: MDN Web Docs: Optional chaining在此处阅读更多内容: MDN Web 文档:可选链接

To get data from the MongoDB database by filtering use below system.通过过滤使用以下系统从 MongoDB 数据库中获取数据。

cars.filter(car => car.email === user.email)?.map(car => {
    return (
        <tr key={car._id}>
            <td>{car.userName}</td>
            <td className=''>{car.email}</td>
            <td>{car.name}</td>
            <td><img src={car.img} alt="" /></td>
        </tr>
    )
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM