【发布时间】:2021-01-03 06:23:37
【问题描述】:
我正在尝试使用 fetch 调用来检索一些 API 数据。不幸的是我不能用它来设置状态。
consructor() {
this.state = {
weather: ""
};
this.search = this.search.bind(this);
}
search(postalCode) {
const url = `https://api.weatherbit.io/v2.0/forecast/daily?&postal_code=${postalCode}&key=${API_KEY}&days=7`;
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
}'
此代码运行良好,并将包含正确数据的对象打印到控制台。
consructor() {
this.state = {
weather: ""
};
this.search = this.search.bind(this);
}
search(postalCode) {
const url = `https://api.weatherbit.io/v2.0/forecast/daily?&postal_code=${postalCode}&key=${API_KEY}&days=7`;
fetch(url)
.then(response => response.json())
.then(data => this.setState({weather: data}))
.catch(error => console.log(error));
}
当我尝试使用数据更新我的状态时,我会收到“this.setState is not a function”错误。我已经在构造函数中绑定了搜索功能。
我什至试过这样绑定它:
fetch(url)
.then(response => response.json())
.then(data => this.setState({ weather: data })).bind(this);
这也不起作用。有人有什么想法吗?
【问题讨论】:
-
只需将大括号括起来 { this.setState({your code}) } 就可以了
-
你在
constructor中使用了super()吗?如果没有,你必须