我在 React 中有以下代码:
export class CryptoInformation extends React.Component {
state = {
cryptoInformation: {}
}
componentDidMount() {
fetch('https://api.coinmarketcap.com/v2/ticker/1/')
.then(response => response.json())
.then(response => {
this.setState({cryptoInformation: response["data"]});
})
.then(response => {
#########This logs to the console 'Bitcoin'#######
console.log(this.state.cryptoInformation.name);
})
}
render() {
return (
<View>
######## Why is this not showing 'Bitcoin' #######
<Text>{this.state.cryptoInformation.name}</Text>
</View>
)
}
}
API 运行良好,我能够获取存储在cryptoInformation
对象中所需的信息。但是,当我尝试显示 JSON 的name
部分时,我没有得到任何文本。为什么会这样?这应该是直截了当的。我呈现的数据有误吗?帮助将不胜感激。谢谢。
----编辑----
返回的数据具有以下结构:
{
"data": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17008162.0,
"total_supply": 17008162.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 9024.09,
"volume_24h": 8765400000.0,
"market_cap": 153483184623.0,
"percent_change_1h": -2.31,
"percent_change_24h": -4.18,
"percent_change_7d": -0.47
}
},
"last_updated": 1525137271
},
"metadata": {
"timestamp": 1525237332,
"error": null
}
}
另外,我没有错误,因为我可以在控制台中看到数据结构。
-----编辑----
我遗漏了一个主要细节。我实际上正在使用 React 360 来创建 Vr 网页。很抱歉遗漏了。
我已经尝试了相同的方法,但没有收到任何错误,它按预期工作。
我唯一改变的是使用<div>
而不是<View>
,<h1>
而不是<Text>
. 因为它是一个反应应用程序。
您必须检查天气是否正确导入此文件。
class CryptoInformation extends React.Component {
state = {
cryptoInformation: {}
}
componentDidMount() {
fetch('https://api.coinmarketcap.com/v2/ticker/1/')
.then(response => response.json())
.then(response => {
this.setState({cryptoInformation: response["data"]});
})
.then(response => {
console.log(this.state.cryptoInformation.name);
})
}
render() {
return (
<div>
<h1>{this.state.cryptoInformation.name}</h1>
</div>
)
}
}
ReactDOM.render(
<CryptoInformation/>,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>