我正在尝试使用类似 axios 命令的 API 从 API 获取数据
function fetchData(apiURL){
let data = [];
let options = {
method: "GET",
url: apiURL,
headers: {
"Access-Control-Allow-Origin": "*"
},
credentials: "include"
};
axios(options)
.then(response => {
data = response.data;
console.log(data);
})
.catch(function (error) {
console.log("System error : " + error);
});
return data;
}
但这将生成数组集,这些数组将存储来自 response.data
的 JSON 数组,每个数组集 100 个。
我在使用 fetch()
检索所有数据时没有遇到问题。我如何才能获得一大堆 JSON 对象的类似响应而不是拆分?
附言。 我已经在
中触发了该功能 componentDidMount() {
const apiURL = process.env.REACT_APP_API;
let tableData = fetchData(apiURL);
console.log("DATA " + JSON.stringify(tableData));
this.setState({tblData : tableData});
}
最佳答案
Axios 请求是异步的并返回 promise ,因此您需要稍微调整您的示例,以便您的函数返回 promise 。
/**
* @return {Promise<T>}
*/
function fetchData(apiURL){
const options = {
method: "GET",
url: apiURL,
headers: {
"Access-Control-Allow-Origin": "*"
},
credentials: "include"
};
return axios(options)
.then(response => {
return response.data;
})
}
现在,当您异步使用此 API 时。
function somethingThatUpdatesThatUI() {
fetchData("/api/foo/bar")
.then((data) => {
//perform updates to UI or state here
})
.catch((err) => {
//alert the users that an error has happened here
})
}
关于javascript - axios 和响应数据集拆分到多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58420680/