将状态绑定到React中map函数内的条件语句

时间:2016-07-08 10:00:43

标签: javascript meteor reactjs

我有一个帖子列表,其中点击一个将切换帖子并显示其评论。我希望根据帖子是否切换来有条件地加载和显示评论,但是我无法在我的方法中访问状态,检查帖子是否被切换。

上下文应该是否与箭头函数自动绑定?

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

1 个答案:

答案 0 :(得分:0)

USe this.setState outside the forEach




getInitialState(){
  return {
  }
}
       componentDidMount() {
            this.state = {};
                
            const posts = this.props.posts;
          
            var newState = {} ;      
            posts.forEach(function(post) {
                    
              newState[post._id] = false;
            });
             
            this.setState({
              state: newState
            }      
          },