繁体   English   中英

未定义的属性“长度”-React教程

[英]property 'length' of undefined - React tutorial

我正在关注一个React教程,但是有一个错误不允许我继续,我尝试了所有操作,但没有给出任何结果,给出了未定义的信息,但是我已经更改了几件事,但无法解决。

埃罗

码:

class PostsManager extends Component {
  state = {
    loading: true,
    posts: [],
  };

  componentDidMount() {
    this.getPosts();
  }

  async fetch(method, endpoint, body) {
    try {
      const response = await fetch(`${API}${endpoint}`, {
        method,
        body: body && JSON.stringify(body),
        headers: {
          'content-type': 'application/json',
          accept: 'application/json',
          authorization: `Bearer ${await this.props.auth.getAccessToken()}`,
        },
      });
      return await response.json();
    } catch (error) {
      console.error(error);
    }
  }

  async getPosts() {
    this.setState({ loading: false, posts: await this.fetch('get', '/posts') });
  }

  async deletePost(post) {
    if (window.confirm(`Are you sure you want to delete "${post.title}"`)) {
      await this.fetch('delete', `/posts/${post.id}`);
      this.getPosts();
    }
  }
    return (
      <Fragment>
        <Typography variant="display1">Posts Manager</Typography>
        {this.state.posts.length > 0 ? (
          <Paper elevation={1} className={classes.posts}>
            <List>
           ....

同意Glup3,但我只使用this.state.posts.length而不是检查长度是否大于0。这样,如果.length未定义或为0,则为false。

{this.state.posts.length ? .... 

假设this.fetch('get', '/posts')正常工作并返回一些您需要实际评估响应的json:

async getPosts() {
    const response = await this.fetch('get', '/posts');
    const json = await response.json();
    this.setState({ loading: false, posts: json });
 }

更多信息, 这里的MDN。

您想渲染<Fragment>...</Fragment>但出现错误。 这是因为this.state.posts为null / undefined并且不能在其中使用长度。

解决方案:设置一个if条件,然后等待它不再为null。

if (this.state.posts != null) {
  return (<Fragment> ... </Fragment>);
}
else {
  return (<div> Loading... </div>); // or something else
}

您的Glup3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM