【问题标题】:Why inside the then() the data exist, and out side doesn't - Axios returning undefined为什么 then() 内部存在数据,而外部不存在 - Axios 返回未定义
【发布时间】:2021-01-29 00:05:05
【问题描述】:

代码是:

var data;

axios.get('http://localhost:3000/api/goodNews').then(result => {
    data = result;  
    console.log(data); //This work
    return data;
});

console.log(data)//this don't work

目标是从 axios 得到答案,用在这段代码所在的组件中。但是,我无法从 Then () 函数中获取此信息。有时它返回未定义,如果你这样做:


    var data;

    data = axios.get('http://localhost:3000/api/goodNews').then(result => {
        return result
    });

    console.log(data)//this don't work

返回 "Promise { }"

我已经试过了:

1

    async function  getData(){
        var response = await axios.get('http://localhost:3000/api/goodNews').then(result => {
            return result
        });

        return response
    }

    var data = getData();

    console.log(data);

2

    const [data, setData] = useState(null)
   
    axios.get('http://localhost:3000/api/goodNews').then(result => {
        setData(result);
        return data;
    }).catch(function (error) {
        console.log(error);
    });
    
    console.log(data);

3


    const [data, setData] = useState(null)

    const getData = async ()=>{

        
        var response = await axios.get('http://localhost:3000/api/goodNews').then(result => {
            return result;
        });

        setData(response)
        return response;
    }

    getData();

    console.log(data);
    

OBS:我在一个 React 组件中,想使用返回的 TML 中的数据

如何从 then() 函数返回数据?

【问题讨论】:

标签: reactjs axios response


【解决方案1】:

您可以使用useState 分配来自then 函数的响应

先定义

const [apiData,setData] = useState(null) 

然后在请求中

更新:

axios.get('http://localhost:3000/api/goodNews').then( res => setData(res))

之后

  console.log(apiData)//the useState value

完整代码

const [data, setData] = useState(null)
useEffect(()=>{
        axios.get('http://localhost:3000/api/goodNews').then(res=> 
    setData(res.data));
 },[])

现在,每当您发送请求并获得响应时,then 函数会将响应添加到 data

【讨论】:

  • 但这再次破坏了代码,出现错误:TypeError:赋值给常量变量。在 C:\Users\refba\github\nextJsTest\.next\server\pages\timeLine.js:4071:10 在 runMicrotasks () 在 processTicksAndRejections (internal/process/task_queues.js:93:5.跨度>
  • 如果我解决这个问题,仍然返回“null”旧值
  • 是的,我试过了。但现在它返回“null”
  • 如果您像我在新的更新答案中那样删除返回怎么办?
  • 我删除它,仍然返回null....我认为需要使用setState
【解决方案2】:

有两种方法可以做到这一点。

  1. 异步/等待
var data;

data = await axios.get('http://localhost:3000/api/goodNews').then(result => {
    return result;
});

  1. 使用promise,无法得到axios调用的结果。

【讨论】:

  • 忘了放json,你应该从第一个then的结果中返回json。
【解决方案3】:

Axios 执行异步请求,因此它的返回值不是实际数据,而是返回一个 Promise 对象。如果想在get请求之外访问axios获取的数据,可以使用axios返回的promise对象。

这里是一个例子 sn-p:

function getSrc() {   
    return axios.get('assist/img/src');
}

getSrc.then(function (response) {
    return response.data; // now the data is accessable from here.
}).catch(function (response) {
    console.log(response);
});

Axios 是这样设计的,因此它可以帮助处理异步任务。希望这能回答您的问题。

【讨论】:

  • 它说 getSrc.then 不是一个函数...(我在一个反应​​组件内部)
【解决方案4】:

实际上当你这样做时:

var data;

data = axios.get('http://localhost:3000/api/goodNews').then(result => {
    return result
});

console.log(data)

那个时候数据还没有现成的,它会记录 Promise 对象。 如果你在函数内部做,你可以使用async-await保留关键字等待值(记住,你只能在async函数内部使用await


function async getData(){
var data;

data = await axios.get('http://localhost:3000/api/goodNews').then(result => {
    return result
});

console.log(data)
}

但是,从技术上讲,您仍在使用 Promise,但形式不同。

【讨论】:

    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2019-08-29
    相关资源
    最近更新 更多