[英]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)
我認為正確的方法是添加一個存儲該變量的變量,但我似乎無法弄清楚該變量的位置,因為這也會引發錯誤。
Array.prototype.filter()
使用第二個參數,該第二個參數將在調用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.