繁体   English   中英

未捕获的类型错误:无法读取未定义的属性“用户名”

[英]Uncaught TypeError: Cannot read property 'username' of undefined

当我导航到外部页面并尝试返回 go 时,我得到 Uncaught TypeError: Cannot read property 'username' of undefined。 在渲染时,它会遇到我返回 false 的 else 语句。 有没有办法避免这个错误被抛出?

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;
                }
            }
        })

错误信息

您可以在此处进行检查并执行以下操作:

 <h2 className="video-owner-name">{videoOwner ? videoOwner.username : ""}</h2>

您可以使用类型安全运算符。

? 是安全导航操作员 它检查变量是 null 还是在模板中未定义。 在 null 和未定义的情况下,该值不会引发错误。

 <h2 className="video-owner-name">{videoOwner?.username}</h2>

第二个选项是使用前面答案中建议的三元运算符。

 <h2 className="video-owner-name">{videoOwner ? videoOwner.username : ""}</h2>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM