javascript - axios 和响应数据集拆分到多个数组

标签 javascript arrays reactjs axios response

我正在尝试使用类似 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/

相关文章:

javascript - 谷歌地图 api 3 上的信息窗口帮助

javascript - Leaflet GeoJSON 图层控件在此脚本中不起作用?

c++ - 制作动态对象数组问题?

android - 莫纳卡不加载 www/index.html

javascript - 如何删除双括号中的字符串?

javascript - 使用 CodeMirror 模块时无法调整 HTML textarea 元素的大小

javascript - 在填充对象数组中查找值 mongodb - lodash

Java 数组按引用传递

spring - AWS 可以与 Spring Boot 和 React 一起使用吗?

reactjs - react native 中的动画可以暂停和重启吗?