1

axios promise の結果が render 関数に表示されない理由がわかりません。ところで、私は 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

サーバーにデータを要求する場合、要求は非同期です。これは、サーバーが応答するのに時間がかかり、ブラウザーが実行を継続することを意味します_getPrice。サーバーは、データに対して何もしていないと応答します。

2番目の問題は、状態または小道具に変更がある場合にのみ、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 に答える
0

stateコンポーネントのまたはが変更された場合にのみ、React はコンポーネントを再レンダリングしますprops。レンダリング サイクル中にデータが変更されても、それらの変数と相互作用しない場合、変更は表示されません。

promise の結果を次のように保存できます。

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 に答える