首页 > 解决方案 > 类组件中的获取请求未返回数据或更新状态

问题描述

我已经重构了一个组件以fetch向数据库添加请求AWS,数据是可访问的,并且可以快速模拟codesandbox工作。但是,当在这种情况下使用时,它会错误地...

TypeError:无法读取未定义未处理拒绝(TypeError)的属性“forEach”:this.setState 不是函数

在控制台中......

{error: null, isLoaded: true, users: Array(0), undefined}

下面的代码...

  constructor() {
    this.mapUserCountries = {};
    this.state = {
      error: null,
      isLoaded: true,
      users: []
    };
  }

  init() {
    this.getUsers = () => {
      fetch(
        "DATABASE"
      )
        .then(res => res.json())
        .then(
          result => {
            this.setState({
              isLoaded: true,
              users: result.users
            });
            console.log(result, this.state);
          },
          error => {
            this.setState({
              isLoaded: true,
              error
            });
          }
        );
    };

    const mappedUsers = this.getUsers();

    console.log(this.state, mappedUsers);

    mappedUsers.forEach(user => {
      const c = user.country;

      if (!this.mapUserCountries[c])
        this.mapUserCountries[c] = { nbUsers: 0, users: [] };
      this.mapUserCountries[c].nbUsers++;
      this.mapUserCountries[c].users.push(user);
    });
  }

  getUsersPerCountry(country) {
    return this.mapUserCountries[country];
  }
}

export default new UsersManager();

标签: javascriptreactjsfetch

解决方案


async init() {
  ...
  const mappedUsers = await this.getUsers();
  ...

你现在处于异步状态。


推荐阅读