我不知道为什么我的axios承诺的结果没有出现在渲染功能中。顺便说一下,我正在使用create-react-app工具。
_getPrice() {
const url = 'https://api.coinbase.com/v2/prices/BTC-USD/spot';
axios.get(url)
.then(function (response) {
//console.log(response.data.data.amount);
let prices = response.data.data.amount;
return prices;
})
}
render() {
return(<div><h3> {this._getPrice()} </h3></div>);
}
_getPrice() {
const url = 'https://api.coinbase.com/v2/prices/BTC-USD/spot';
axios.get(url)
.then(function (response) {
//console.log(response.data.data.amount);
let prices = response.data.data.amount;
return prices;
})
}
render() {
return(<div><h3> {this._getPrice()} </h3></div>);
}
答案 0 :(得分:0)
只有当组件的state
或props
发生更改时,React才会重新呈现组件。如果数据在渲染周期中发生变化,但未与这些变量进行交互,则不会显示更改。
您可以将承诺的结果保存到州:
getInitialState() {
return {prices: undefined}
}
componentDidMount() {
const url = 'https://api.coinbase.com/v2/prices/BTC-USD/spot';
axios.get(url)
.then(function (response) {
//console.log(response.data.data.amount);
let prices = response.data.data.amount;
this.setState({prices: prices});
}.bind(this))
}
render() {
return(<div><h3> {this.state.prices} </h3></div>);
}
答案 1 :(得分:0)
首先你不能在渲染函数中调用函数,如果你想更新你的视图,你必须更新状态或道具......
答案 2 :(得分:0)
当向服务器请求数据时,请求是异步的,这意味着服务器需要时间来响应并且浏览器将继续执行,而不是说,在您当前的实现中,您将在您的{中返回承诺{1}}函数,然后当服务器响应时,你没有对数据做任何事情。
第二个问题是,只有当状态或道具发生变化时,react才会重新渲染组件,并且在当前的实现中,你不会改变任何一个。
以下是您需要如何操作才能使其正常运行的示例。
_getPrice
祝你好运!