【发布时间】:2019-11-20 13:28:27
【问题描述】:
我正在尝试过滤 ReactJs 中的对象数组。但是,当我尝试通过 userId 过滤对象时,数组返回为空。
为了确保我的收藏夹道具已更新,我在 componentDidMount() 函数中记录了所有相关信息。 console.log 显示我的收藏夹道具确实是一个包含对象的数组。
componentDidUpdate() {
console.log(this.props.favorites);
console.log(this.props.favorites[0].userId);
console.log(this.filterFavorites());
}
filterFavorites() {
return this.props.favorites.filter((favorite) => {
return favorite.userId === this.props.currentUserId;
});
}
但是,我希望返回一个数组,其中包含由当前用户 ID 过滤的对象。相反,我得到了一个空数组
【问题讨论】:
-
你确定
favorite.userId === this.props.currentUserId会在循环中返回true吗? -
也许
currentUserId是错误的类型 -
您是否正确地将
filterFavorites绑定到类实例,以便您可以访问道具? Your code executes just fine,所以要么你没有绑定,要么你没有你期望的值 -
@Aluan 谢谢,我刚刚意识到 currentUserId 没有在 mapStateToProps 中正确设置并且返回为未定义,所以比较总是返回 false。
标签: javascript arrays reactjs filter