gpt4 book ai didi

javascript - 类组件中的获取请求未返回数据或更新状态

转载 作者:行者123 更新时间:2023-12-02 21:40:21 25 4
gpt4 key购买 nike

我重构了一个组件,向 AWS 数据库添加 fetch 请求,数据可访问,并且可以在 codesandbox 上进行快速模拟。然而,当在这种情况下使用时,它会出错...

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

您现在处于异步状态。

关于javascript - 类组件中的获取请求未返回数据或更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60380841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com