I'm trying to access the state of my component but I keep getting an error saying Cannot read property 'state' of undefined
.
render: function() {
return (
<div className='arsenal-feed'>
<h1>{this.state.query}</h1>
<SearchInput query={this.state.query} onUserInput={this.onChangeHandler}/>
<ul>
{
this.state.posts.filter(function(val, i, arr) {
if (val.body.indexOf(this.state.query) !== -1) {
return <li key={i}>{val.body} <ActionButtons key={i}/></li>
}
})
}
</ul>
</div>
);
}
It's this line which throws the error:
if (val.body.indexOf(this.state.query) !== -1)
I think the correct way would be to add a variable that stores the outside this but I can't seem to figure out where to put it because this too throws errors.
Array.prototype.filter()
takes a second argument which will be used as the this
value when calling the filter function, so pass this
as a second argument.
<ul>
{
this.state.posts.filter(function(val, i, arr) {
if (val.body.indexOf(this.state.query) !== -1) {
return <li key={i}>{val.body} <ActionButtons key={i}/></li>
}
}, this)
}
</ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.