2016-09-18 43 views
0

我不知道爲什麼我的axios promise的結果不會顯示在呈現函數中。順便說一句,我正在使用create-react-app工具。Ajax請求不會在呈現函數中顯示

_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>); 
} 

+1

Wel ......你可以在'componentDidMount'和'_getPrice'函數中調用'this._getPrice()',在獲得數據之後,你可以使用'setState'將它存儲在狀態中,並且可以顯示數據狀態如果數據不存在,您可以顯示加載消息..,這有幫助嗎? –

回答

0

REACT僅重新呈現組件時,無論是state或成分變化的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>); 
} 
0

第一你不能調用一個函數在渲染函數返回,如果你想更新你的觀點,你必須更新狀態或道具..

0

當向服務器請求數據時,請求是異步的,這意味着服務器需要時間來響應,並且瀏覽器會繼續執行,而不是說,在您當前的實現中,您將返回一個承諾你的_getPrice函數,然後當服務器響應你沒有對數據做任何事情。

第二個問題是反應只會在狀態或道具發生變化時重新渲染組件,並且在當前的實現中您沒有更改任何這些組件。

下面是一個示例,說明如何使其工作。

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> 
    ); 
    } 
} 

祝你好運!