如何在过滤器函数中访问 React 组件的 this.state?
How can I access this.state of React component inside of a filter function?
我正在尝试访问我的组件的状态,但我一直收到一条错误消息 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>
);
}
正是这一行引发了错误:
if (val.body.indexOf(this.state.query) !== -1)
我认为正确的方法是添加一个存储外部 this 的变量,但我似乎无法弄清楚将它放在哪里,因为这也会引发错误。
Array.prototype.filter()
接受第二个参数,在调用过滤器函数时将用作 this
值,因此将 this
作为第二个参数传递。
<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>
我正在尝试访问我的组件的状态,但我一直收到一条错误消息 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>
);
}
正是这一行引发了错误:
if (val.body.indexOf(this.state.query) !== -1)
我认为正确的方法是添加一个存储外部 this 的变量,但我似乎无法弄清楚将它放在哪里,因为这也会引发错误。
Array.prototype.filter()
接受第二个参数,在调用过滤器函数时将用作 this
值,因此将 this
作为第二个参数传递。
<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>