类组件中的提取请求未返回数据或更新状态 [英] Fetch request in class component is not returning data or updating state

查看:50
本文介绍了类组件中的提取请求未返回数据或更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have refactored a component to add a fetch request to an AWS database, the data is accessible and a quick mock on codesandbox works. However when used in this context it errors as...

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

TypeError: Cannot read property 'forEach' of undefined Unhandled Rejection (TypeError): this.setState is not a function

并在控制台中...

{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();

推荐答案

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

您现在处于异步土地.

这篇关于类组件中的提取请求未返回数据或更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆