首页 > 解决方案 > TypeError:无法在 React 中读取未定义的属性(读取 'id')

问题描述

我已经建立了一个网站,但是在 3 次后按“加载更多”按钮时遇到问题。它给了我一个错误“TypeError:无法读取未定义的属性(读取'id')”......我猜切片和映射函数有问题!PS我试图将“id”调用到其他组件但徒劳无功!

class PostsList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      posts: [],
      visible: 3,
      error: false
    };

    this.loadMore = this.loadMore.bind(this);
  }

  loadMore() {
    this.setState((prev) => {
      return {visible: prev.visible + 3};
    });
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts").then(
      res => res.json()
    ).then(res => {
      this.setState({
        posts: res
      });
    }).catch(error => {
      console.error(error);
      this.setState({
        error: true
      });
    });
  }

  render() {
    const { classes } = this.props;

    return (
      <div className={classes.section}>
        <h2 className={classes.title}>Latest news</h2>
        <div>
          <GridContainer>
            {
              this.state.posts.slice(0, this.state.visible).map((post, i) => {
               return (
                  <PostCard key={i}
                  id={posts[i].id}
                  date={posts[i].date} 
                  fbimg={posts[i].fbimg} 
                  description={posts[i].description} 
                  fbpost={posts[i].fbpost}
                  />
                );
              })
            } 
          </GridContainer> 
           <GridContainer>
            <GridItem>
            {this.state.visible < this.state.posts.length &&
              <Button 
                color="info"
                onClick={this.loadMore} 
              >
              Load more
              </Button>
            }
            </GridItem>
          </GridContainer>
      </div>
    </div>
    );
  }
}

先感谢您!!!

标签: javascriptreactjs

解决方案


posts未在您的渲染函数中定义。你的意思是this.state.posts

此外,如果您的函数中已经有post可用的单曲,则无需使用索引来访问帖子。map所以posts[i].id改为post.id.


推荐阅读