[英]Why the code in react was working, but few weeks later it has error? TypeError: Cannot read properties of undefined (reading 'slice')
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')但是今天我发现网站有错误,它说: 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 {}?我不应该在 {} 里面写 function 吗?
The error is telling you that name
has an undefined
value.该错误告诉您name
具有undefined
的值。 So whatever is using this component isn't (or at least isn't always) providing a value for the name
prop.因此,无论使用该组件的是什么,都不会(或至少不总是)为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.有多种构建逻辑的方法,但总的来说,重点是在尝试使用变量之前检查变量是否具有值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.