为什么在 then() 内部存在数据,而外部不存在 - Axios 返回未定义

Why inside the then() the data exist, and out side doesn't - Axios returning undefined

密码是:

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 () 函数中获取此信息。有时它 return 未定义,如果您这样做:


    var data;

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

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

是return“承诺{}”

我已经试过了:

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 组件中,想使用 returning TML

中的数据

如何return 来自 then() 函数的数据?

您可以使用 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

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

  1. async/await
var data;

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

  1. 使用promise,无法获取axios调用的结果

Axios 执行异步请求,因此它的 return 值不是实际数据,但它 return 是一个承诺对象。如果想在get请求之外访问axios获取的数据,可以利用axiosreturned的promise对象

这是一个示例片段:

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 就是这样设计的,所以它可以帮助处理异步任务。希望这能回答您的问题。

实际上当你这样做的时候:

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,但形式不同。