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

Bind state to conditional statement inside of map function in React

本文关键字:内部 条件 语句 映射函数 状态 绑定 React      更新时间:2023-09-26

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

上下文不是应该自动绑定箭头函数吗?

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