我在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>
)
}
}
该应用程序接口工作得很好,我能够获得需要存储在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网页。抱歉遗漏了这一点。
发布于 2018-09-18 13:37:07
我已经尝试了同样的方法,但没有得到任何错误,它的工作如预期。
我唯一改变的是我使用了<div>
insted <View>
,<h1>
代替了<Text>
。因为它是一个react应用程序。
你必须检查你是否正确地导入了这个文件。
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>
https://stackoverflow.com/questions/52379396
复制相似问题