javascript - 我可以在我的 console.log 中显示 API 数据,但我不能用它来设置状态。. . 我该如何设置状态?(获取,反应本机)
问题描述
constructor(props){
super(props);
if(myCounter.intCoin == 0){
this.fetchCoinsAPI("litecoin", "usd");
this.coinMet("ltc");
}
this.state = {
X: new Animated.Value(0),
data: undefined,
arrayLength: undefined,
line: undefined,
dataReverse: undefined,
properties: undefined,
lineLength: undefined,
color: "#CDCDCD",
translate: new Animated.Value(-500),
coinColor: {
btc: {color:"#31055A", selected:false},
eth: {color:"#31055A", selected:false},
ltc: {color:"#31055A", selected:false},
},
amountCombined: "USD 0.00",
currency: "USD ",
mainCurrency:"usd"
};
console.log(this.state.data);
}
fetchCoinsAPI(coinID, currency){
return fetch(`https://api.coingecko.com/api/v3/coins/${coinID}/market_chart?vs_currency=${currency}&days=7`, {
method: 'GET'
})
.then(res => res.json())
.then(resp => this.setState({data: resp.prices}))
.catch(err => {console.log(err)});
}
**我正在从远程 API 获取数据以绘制图表**
它返回undefined
状态数据,但是当我console.log(resp.prices)
在.then()
它工作时。
我被难住了,有人能指出我错过了什么吗?
谢谢,杰德男孩。
解决方案
我想分享三个观察结果。
绑定方法
fetchCoinsAPI
使用Component.setState
,因此在构造函数中将上下文绑定fetchCoinsAPI
到组件
constructor(props){
this.fetchCoinsAPI = this.fetchCoinsAPI.bind(this);
}
不要在构造函数中调用外部源
把它们放进去componentDidMount
componentDidMount {
this.fetchCoinsAPI("litecoin", "USD");
}
JavaScript 是异步的
由于 JavaScript 的异步行为,数据将不可用。阅读如何从异步调用返回响应?
推荐阅读
- javascript - 更改地址栏中的整个 url (Javascript)
- jquery - 如何解决重定向到 undefiend 路由 laravel?
- scala - 使用 scala 猫检查非空字段的组合
- windows - SIGUSR1/2 for Go 的 Windows 等效项是什么?
- ios - 在应用程序外打开 react native expo 应用程序外部链接
- google-cloud-platform - 从 GCP 中的日志接收器创建 BigQuery 数据集
- laravel - 在 Laravel 布局页面中获取当前登录用户
- git - 仅将不同的存储库移动到一个更改结构中
- keycloak - Keycloak URL 片段在登录时不会消失
- ruby-on-rails - 带有 Systemd 的 Puma 无法启动