1

我不知道为什么我的 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>);
}

4

3 回答 3

0

首先你不能在渲染函数中调用一个函数作为回报,如果你想更新你的视图,你必须更新状态或道具......

于 2016-09-19T04:06:16.080 回答
0

stateReact 仅在组件的或更改时重新渲染组件props。如果数据在渲染周期中发生了变化,但没有与这些变量交互,那么这些变化将不会显示出来。

您可以将您的承诺结果保存为如下所示:

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>);
}
于 2016-09-18T20:44:34.470 回答
0

当向服务器请求数据时,请求是异步的,这意味着服务器需要时间来响应并且浏览器将继续执行,而不是说,在您当前的实现中,您在_getPrice函数中返回一个承诺,然后当服务器响应您没有对数据做任何事情。

第二个问题是,当状态或道具发生变化时,react 只会重新渲染组件,而在您当前的实现中,您不会更改任何内容。

这是一个示例,说明您需要如何执行它才能使其正常工作。

class YourComponent extends Component {
  state = {
    prices: 0,
  };

  componentDidMount() {
    const url = 'https://api.coinbase.com/v2/prices/BTC-USD/spot';
    axios.get(url)
      .then((response) => {
        let prices = response.data.data.amount;
        this.setState({ prices });
      });
  }

  render() {
    const { prices } = this.state;

    return(
      <div>
        <h3> {prices} </h3>
      </div>
    );
  }
}

祝你好运!

于 2016-09-19T08:36:00.973 回答