如何在变量Fetch API中存储异步数据

问题描述 投票:-1回答:2

我正在开发一个项目,使用Laravel作为后端,React作为前端。

每当用户点击登录时,将打开一个模态,在提交时将提取用户持有者令牌。

这些获取函数都位于AuthService.js

export function getLoginToken(email, password) {
    fetch("/api/login", {
        method: "post",
        credentials: 'include',
        headers: {
            'Accept': 'application/json',
            "Content-type": "application/json",
        },
        body: JSON.stringify({
            'email': email,
            'password': password
        })
    }).then((response) => response.json())
        .then((responseJSON) => {
        return responseJSON;
    })
}

Nav组件是登录按钮所在的位置,因此我导入并使用我在AuthService.js中创建的函数

当我在实际的getLoginToken函数中控制日志json结果时,没有问题。因为将它放在.then()中它等待它完成所以它不会导致未定义。

现在..在导航组件内部,有一个绑定到登录按钮的onClick函数,它将执行AuthService.getLoginToken(email, password)

实际问题:

我想将响应数据存储在变量中,但我一直未定义。这是因为我试图在同步函数中插入异步数据。

我也尝试过:

AuthService.getLoginToken(loginEmail, loginPassword).then((result) => {
            this.setState({
                token: result
            });
        });

但这也将返回:无法读取未定义的属性'then'。

有想法该怎么解决这个吗?

javascript reactjs asynchronous fetch
2个回答
-2
投票

试试这个

export function getLoginToken(email, password) {
  return fetch("/api/login", {
    method: "post",
    credentials: 'include',
    headers: {
        'Accept': 'application/json',
        "Content-type": "application/json",
    },
    body: JSON.stringify({
        'email': email,
        'password': password
    })
}).then((response) => response.json())
    .then((responseJSON) => {
    return responseJSON;
})
}

正确的方法是使用像redux这样的状态管理工具


-2
投票

您可以使用async await。或者如果你正在使用redux,请使用redux-thunk。

© www.soinside.com 2019 - 2024. All rights reserved.