我正在尝试从 Coindesk API 获取比特币价格。这是我的应用程序:
import React from 'react';
import ReactDOM from 'react-dom';
let bpiURL = 'http://api.coindesk.com/v1/bpi/currentprice.json';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
fetch(bpiURL)
.then(response => response.json())
.then(res => {
console.log(res);
return res;
})
.then(response => this.setState({ data: response }));
}
render() {
return (
<div>
<p>
{this.state.data.disclaimer}
</p>
</div>
);
}
}
ReactDOM.render(<App />, 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>
问题是它适用于 this.state.data.disclaimer
和 this.state.data.chartName
但不适用于 this .state.data.bpi.USD.rate
这是我需要的。我怎样才能得到那个值?
编辑:这是我从 this.state.data
得到的:
Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead. in p (at index.js:42) in div (at index.js:37) in App (at index.js:49)
最佳答案
this.state.data.bpi.USD.rate
有效,但仅在请求完成后有效。在此之前,this.state.data.bpi
将给出 undefined
,并尝试访问 USD
将导致错误。
您可以将默认的 data
更改为 null
,并在渲染方法中使用它之前检查是否设置了 data
。
示例
let bpiURL = "https://api.coindesk.com/v1/bpi/currentprice.json";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
fetch(bpiURL)
.then(response => response.json())
.then(response => this.setState({ data: response }));
}
render() {
return (
<div>
<p>{this.state.data && this.state.data.bpi.USD.rate}</p>
</div>
);
}
}
ReactDOM.render(<App />, 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>
关于javascript - 需要有关在 React 应用程序中解析来自此 API 的 JSON 数据的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51517887/