Take a look at the following code:
const MyComponent = props => (
<div>{props.user.info.addresss[0].city || 'No city information yet'}</div>
)
Copy the code
This code is plain and simple, but again, the following matching error is quite common:
Uncaught TypeError: Cannot read property '0' of undefined
Copy the code
There is no need to describe the reasons for the error. There are two intuitive solutions: restrict all layers of data from being empty by means of human governance, or add some judgments as follows:
const MyComponent = props => (
<div>
{(props.user.info.addresss && props.user.info.addresss[0].city) || 'No city information yet'}
</div>
)
Copy the code
Have to say, this code is very tired, looking very ugly, more on this code there are several layers of value, each layer may be wrong, if you judge the code into a tuo ****.
It is time to use the new Babel plug-in babel-plugin-transform-optional-chaining.
const MyComponent = props => ( <div> {props? .user? .info?.addresss?.[0]?.city ||'No city information yet'}
</div>
)
Copy the code
How about that? Is that a lot easier