javascript - 类组件中的获取请求未返回数据或更新状态
问题描述
我已经重构了一个组件以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();
解决方案
async init() {
...
const mappedUsers = await this.getUsers();
...
你现在处于异步状态。
推荐阅读
- reactjs - 反应:微数据类型范围被奇怪地传递
- amazon-web-services - .Net Core - 启用 DI 的 AWS Lambda 项目
- c++ - Qt - 两个文本编辑之间的关系
- c++11 - 如何在特定的内存位置创建大小可变的类的实例?
- c# - 执行 Linq.Groupby C# 后如何获得计数
- spring - 重新平衡后 Kafka 消费者无限期挂起
- html - mailto不从chrome中的文本区域发送文本
- python-3.x - 将 CNN 应用于短时傅里叶变换?
- azure - 托管环境为什么设置为生产,host.json 和 local.settings.json 之间的区别
- python-3.x - 使用 Cython 和外部多线程 C 库时的未定义行为