数组过滤器在React.js中返回空数组

时间:2019-07-10 21:23:14

标签: javascript arrays reactjs filter

我正在尝试过滤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过滤的对象。相反,我得到了一个空数组

1 个答案:

答案 0 :(得分:-2)

默认情况下,过滤器没有绑定this的任何内容;是undefined,则必须在函数正文之后传递此引用。

W3FTW

    filterFavorites() {
        return this.props.favorites.filter((favorite) => {
            return favorite.userId === this.props.currentUserId;
        }, this);
    }
相关问题