问题
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: Cannot read property 'forEach' of undefined Unhandled Rejection (TypeError): this.setState is not a function
and in the console...
{error: null, isLoaded: true, users: Array(0), undefined}
code below...
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();
回答1:
async init() {
...
const mappedUsers = await this.getUsers();
...
You're in async land now.
回答2:
There is no defined setState function on the UsersManager class, you will need to create that function
回答3:
First, you need to return promise in order to await
it
this.getUsers = () => {
return 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
});
}
);
};
or use implicit return () => fetch(...)
then,
async init() {
...
const mappedUsers = await this.getUsers();
}
// or
init() {
...
this.getUsers().then((mappedUsers) => { ... });
}
来源:https://stackoverflow.com/questions/60380841/fetch-request-in-class-component-is-not-returning-data-or-updating-state