aBloomer aBloomer - 3 months ago 9
Javascript Question

How to use this.state in my filter function when render component?

Below is my code...

somarray.user.filter(function(ele, index) {
if(this.state.showAllUser == false) {
return (index < 3)
}
else {
return true
}
})


When I render my component, the 'this.state.showAllUser' inside this filter function is undefined.

How to fix this problem?

Answer

this isn't defined correctly in the function. Fix it by binding it so that it has the correct definition.

 somarray.user.filter(function(ele, index) {
       if(this.state.showAllUser == false) {
        return (index < 3)
       }
       else {
        return true
       }
  }.bind(this))