问题
I recently learned about optional chaining in Javascript and have been making use of it in a React/NodeJS project. 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
)
{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
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!
回答1:
If the chaining fails, the expression will evaluate to undefined
.
When a child is evaluated to undefined
, it just won't render.
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:
{ 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.
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.
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).
回答2:
The optional chaining way to your problem is:
{items?.map?.(postListItem => ....)
Read more here: MDN Web Docs: Optional chaining
来源:https://stackoverflow.com/questions/60165042/is-it-possible-to-combine-optional-chaining-with-arrays-and-map-in-javascript