【问题标题】:Array filter returning an empty array in Reactjs数组过滤器在 Reactjs 中返回一个空数组
【发布时间】: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


【解决方案1】:

默认情况下,过滤器没有this 绑定到任何东西;它是undefined,你必须在函数体之后传递这个引用。

W3FTW

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

【讨论】:

  • 这不是真的,因为箭头函数会为您完成绑定。
猜你喜欢
  • 1970-01-01
  • 2021-05-06
  • 2021-11-13
  • 2019-04-23
  • 1970-01-01
  • 2023-01-25
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多