Filtering A List With React

后端 未结 4 1445
不知归路
不知归路 2021-02-13 18:55

Hmm, I don\'t see my omission, but I get a blank page with a console error saying:

Users.js:9 Uncaught TypeError: Cannot read property \'filter\' of undefined
           


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-13 19:49

    You are calling .friend on the list itself when that's a property of each object in your array. You are also using .filter, but I don't think you're using it correctly here. .filter will return an array with certain elements where the function passed in returns a truthy value. Here's how you could do it with .filter:

    var nonFriends = this.props.list.filter(function (user) {
      return !user.friend;
    });
    
    var friends = this.props.list.filter(function (user) {
      return user.friend;
    });
    
    return (
      

    Friends:

      { friends }

    Non Friends:

      { nonFriends }
    );

    You could also do a .forEach for 1 pass through the array if the array is large:

    var nonFriends = [], friends = [];
    
    this.props.list.forEach(function (user) {
      if (user.friend) {
        friends.push(user);
      } else {
        nonFriends.push(user);
      }
    });
    
    // now render friends and nonFriends
    

提交回复
热议问题