[英]Using axios to fetch data from an API which has an API attribute in it in react
我正在使用react從starwars api( https://swapi.co/ )獲取數據。 它具有homeworld屬性,該屬性調用另一個api來獲取有關homeworld的詳細信息。 我嘗試在另一個axios.get()中使用axios.get()來獲取"${results.homeworld}"
(PFA代碼)的詳細信息,但它不返回任何內容。 不知道為什么會這樣,即使我更改axios.get請求,我也無法更新狀態。 這是我第一次搜索,即盧克·天行者。 我應該如何更改每個請求的狀態以及如何處理初始JSON對象內的homeworld API。此外,我在位置0的JSON中遇到Unexpected token <錯誤消息,確實嘗試了在線幫助,但仍然存在相同的問題。
import React from "react";
import axios from "axios";
class Axiosa extends React.Component {
constructor(props) {
super(props);
this.state = { data: {}, name: "", homeplanet: "", species: "" };
}
fetchStarwars() {
axios
.get("https://swapi.co/api/people/3/")
//.then(results => results.text())
.then(results => results.json())
.then(results => {
let x = `"${results.homeworld}"`;
console.log(`"${results.homeworld}"`);
axios
.get(x)
.then(resultshomeworld => {
resultshomeworld.json();
console.log(resultshomeworld);
})
.then(results => {
this.setState({ homeplanet: results.name });
});
this.setState({ data: results, name: results.name, isLoading: false });
});
}
componentDidMount() {
this.fetchStarwars();
}
render() {
console.log(this.state.homeplanet);
return (
<div className="App">
<span>{this.state.name}</span>
<div>{this.state.homeplanet}</div>
</div>
);
}
}
export default Axiosa;
在構造函數中綁定fetchStarwars函數
constructor(props) {
super(props);
this.state = { data: {}, name: "", homeplanet: "", species: "" };
this.fetchStarwars = this.fetchStarwars.bind(this);
}
嘗試從第二個then
執行所有操作, then
在第一個內部執行阻塞操作,或者讓第一個return Promise.resolve(result.json());
因此它可以訪問降低的承諾值。
使用嵌套的第二個axios調用執行相同的操作。
fetchStarwars() {
axios.get("https://swapi.co/api/people/3/")
.then(result => {
let results = result.json();
let x = `"${results.homeworld}"`;
console.log(`"${results.homeworld}"`);
axios.get(x)
.then(results => {
this.setState({ homeplanet: results.json().name });
});
this.setState({
data: results,
name: results.json().name,
isLoading: false
});
});
}
此外,一定要還結合this
到fetchStarwars
在構造函數中。
H對您的代碼進行了一些更改。 您在fetchStarwars
函數中需要this
功能,可以通過Nitha所說的bind
或使用arrow函數來實現。
在這里查看工作樣本
import React from "react"; import axios from "axios"; import {render} from "react-dom" class Axiosa extends React.Component { constructor(props) { super(props); this.state = { data: {}, name: "", homeplanet: "", species: "" }; } fetchStarwars = () => { axios .get("https://swapi.co/api/people/3/") .then(response => { let results = response.data let x = results.homeworld; this.setState({ data: results, name: results.name, isLoading: false }); return axios.get(x) }) .then(results => { this.setState({ homeplanet: results.data.name }); }); } componentDidMount() { this.fetchStarwars(); } render() { console.log(this.state); return ( <div className="App"> <span>{this.state.name}</span> <div>{this.state.homeplanet}</div> </div> ); } } render(<Axiosa />, document.getElementById('root'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.