未捕获的类型错误:无法读取未定义的属性“用户名”
2020-07-04
1091
当我导航到外部页面并尝试返回时,我收到 Uncaught TypeError: Cannot read property 'username' of undefined。渲染时,它会命中 else 语句,我在该语句中返回 false。有没有办法避免抛出此错误?
render() {
const videos = this.randomHomeList();
const users = this.props.users;
const videoList = videos.map(video => {
if (video) {
const owner = users.filter(user => user.id === video.owner_id)
if (owner) {
const videoOwner = owner.find(user => user.username)
return (
<ul key={video.id} >
<div className="home-list-item">
<div className="home-video-header">
<h2 className="home-video-header-1">Added to</h2>
<h2 className="home-video-header-2">Foxeo Staff Picks</h2>
</div>
<Link to={`/play/${video.id}`}>
<video
className="home-video"
src={video.video_url}
poster=""
width="320"
height="240"
>
</video>
</Link>
<h2 className="video-title">{video.video_title}</h2>
<h2 className="video-upload-date">uploaded {this.dateCreated(video.created_at)}</h2>
<h2 className="video-owner-name">{videoOwner.username}</h2>
</div>
</ul>
)
} else {
return false;
}
}
})
2个回答
您可以在此处进行检查并执行以下操作:
<h2 className="video-owner-name">{videoOwner ? videoOwner.username : ""}</h2>
Raghvender Kataria
2020-07-04
您可以使用类型安全运算符。
? 是安全导航运算符 。它检查模板中的变量是否为 null 或未定义。如果为 null 和未定义,该值不会引发错误。
<h2 className="video-owner-name">{videoOwner?.username}</h2>
第二个选项是使用上一个答案中建议的三元运算符。
<h2 className="video-owner-name">{videoOwner ? videoOwner.username : ""}</h2>
khush
2020-07-04