React

2016-07-08 62 views
0

將映射狀態綁定到映射函數內部的條件語句我有一個帖子列表,其中點擊一個將切換帖子並顯示其評論。我希望根據帖子是否被切換來有條件地加載和顯示評論,但是我無法在我的方法中檢查帖子是否被切換。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 
+0

您沒有使用箭頭功能與'forEach'在'componentDidMount'並記住你不能直接分配給'state'。你必須通過'setState'。 –

+0

你是對的,但狀態正在設置正確,我的點擊處理程序(只有發佈的類的部分)與'this'顯式綁定工作正常(onClick = {this.togglePost.bind(this,post._id)}例如)。 – oskare

回答

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 
      }  
      }, 
+0

仍然沒有工作..我張貼精簡的代碼,我知道從類中的其他函數調用這個明確的約束,該狀態設置正確。即例如onClick = {this.togglePost.bind(this,post._id)}正常工作。 – oskare

+0

將getInitial狀態添加到您的組件 –