Last week my code was working as below:
function UserCard({ user }) {
const { name, birthday, _id, url, area } = user
//.........
//.........
//.........
return (
<div>
<img src={url.replace('upload/', 'upload/w_300,h_300,c_limit/')} className="UserCard-img" alt="user-img" />
<h3>{name.slice(0, 1).toUpperCase() name.slice(1).toLowerCase()}</h3>
</div>
);
}
But today I found the website had error, it said: TypeError: Cannot read properties of undefined (reading 'slice') TypeError: Cannot read properties of undefined (reading 'replace')
And then I remove 'slice' and 'replace', then it's working now. These kind of things happened twice already, why the code is unstable? I shouldn't write function inside {}?
CodePudding user response:
The error is telling you that name
has an undefined
value. So whatever is using this component isn't (or at least isn't always) providing a value for the name
prop.
You can use optional chaining to only try to de-reference the value if one exists:
name?.slice(0, 1).toUpperCase()
Or perhaps not display the element at all if there is no value to display:
{ name ?
<h3>{name.slice(0, 1).toUpperCase() name.slice(1).toLowerCase()}</h3> :
null
}
There are a variety of ways to structure the logic, but overall the point is to check if the variable has a value before trying to use it.