將映射狀態綁定到映射函數內部的條件語句我有一個帖子列表,其中點擊一個將切換帖子並顯示其評論。我希望根據帖子是否被切換來有條件地加載和顯示評論,但是我無法在我的方法中檢查帖子是否被切換。React
上下文是不是應該自動綁定箭頭函數?
var PostList = React.createClass({
componentDidMount() {
this.state = {};
const posts = this.props.posts;
posts.forEach(function(post) {
this.state[post._id] = false;
});
},
isToggled(post) {
return this.state[post];
},
render: function() {
var postList = posts.map((post,index) => (
<div class=「post」>
{post.content}<br/>
{this.isToggled(post._id) ?
<Comments postId={post._id}/>
:''}
</div>
))
}
結果:
TypeError: Cannot read property 'idyadayada' of null
您沒有使用箭頭功能與'forEach'在'componentDidMount'並記住你不能直接分配給'state'。你必須通過'setState'。 –
你是對的,但狀態正在設置正確,我的點擊處理程序(只有發佈的類的部分)與'this'顯式綁定工作正常(onClick = {this.togglePost.bind(this,post._id)}例如)。 – oskare