我想從api端點獲取數據並將其顯示在反應組件上。如何獲得承諾價值以反應組件?
當我根據來自state.trainData
的數據通過映射制定組件時,我還需要從另一個api端點獲取數據,用於state.trainData
的每個元素。
我正在使用幫助函數來獲取我的數據,但那是我遇到了障礙。我確實得到的數據很好,但問題是我不能把它放在一個變量左右,以將它放在一個組件。
在調用getSpecificTrainDetails
之後的渲染函數中,我得到了關於response.data
的數據。我一直在嘗試兩個小時來弄清楚如何獲取數據並將其放置在所需的組件中,但我無處可去!非常感謝幫助。
componentDidMount =() => {
axios.get('https://rata.digitraffic.fi/api/v1/live-trains?station=SLO')
.then((response) => {
//console.log(response.data);
this.setState({
trainData: response.data,
});
}).catch((error) => {
console.log(error);
});
}
getSpecificTrainDetails = (trainNum, date) => {
let apiLink = "https://rata.digitraffic.fi/api/v1/compositions/";
let apiConstructedLink = apiLink + trainNum + "?departure_date=" + date;
return axios.get(apiConstructedLink)
.then((response) => {
return response;
}).catch((error) => {
console.log(error);
});
}
render(){
let content = this.state.trainData.map((item, i) => {
this.getSpecificTrainDetails(item.trainNumber, item.departureDate).then((response) => {
console.log(response.data);
});
return <Popup key={i}
<Card> //VALUE FROM 1ST API GOES HERE!!! </Card>
// VALUE FROM 2ND API GOES HERE!!
</Popup>;
});
}
例如從第一API我得到的列車號和日期,並在此日期和號碼一起第二API通過我得到的列車信息。
要清楚,你希望把'response.data'在'彈出'組件? – AGE
@AGE確實是的! –
您應該將其作爲''屬性並在'Popup'內傳遞,您可以在'props'中接收它。您是否嘗試過?另外,mdziekon的答案還有很多需要改進的地方,不管你問什麼 –
AGE