未捕获的TypeError:无法读取未定义的属性“用户名”

时间:2020-07-04 14:00:02

标签: javascript html react-redux

我收到未捕获的TypeError:当我导航到外部页面并尝试返回时,无法读取未定义的属性“用户名”。在渲染时,它会击中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;
                }
            }
        })

error message

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

?是安全导航操作员。它检查变量是null还是在模板中未定义。如果为null且未定义,则该值不会引发错误。

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

第二个选择是使用上一个答案中建议的三元运算符。

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