【问题标题】:React async await not working with function component反应异步等待不适用于功能组件
【发布时间】:2021-12-31 18:21:29
【问题描述】:

服务类方法:

logInUser = (model) => {

        fetch(this.urlService.authUrl, {
            method: 'POST',
            body: model,
            headers: { 'Content-Type': 'application/json' },
        }).then((res) => { return res.json() })
            .then((data) => {
                console.log(data);
                return data;
            });
    }

我正在尝试从下面的到达组件中使用上述方法,

const handleFormSubmit = (e) => {
        e.preventDefault();
        login(e);
    };

组件中的登录功能看起来,

const login = async (e) => {
        const data = await auth.logInUser(JSON.stringify({
            user_name: e.target.elements.user_name?.value,
            password: e.target.elements.password?.value,
        }));
        if (data?.status) {
            sessionStorage.setItem("logged_in_user_X_token", data?.data?.token);
            history.push("/dashboard");
        }
        else {
            debugger;
            setModalHeader(data?.message ?? "authentication_failed");
            setModalBody(data?.data ?? "invalid_credentials");
            setShowModal(true);
        }
    }

但是这里data 总是显示 null 并转到 else 部分但是当我调试代码时我可以看到它正在从 logInUser 方法。

【问题讨论】:

  • 如果你在异步登录函数中使用 console.log data 会得到什么?在检查数据状态之前。

标签: reactjs async-await


【解决方案1】:

你忘记了returnlogInUser中的Promise。这就是为什么await auth.logInUser(..) 的输出是undefined

logInUser = model => {
    return fetch(this.urlService.authUrl, {
        method: "POST",
        body: model,
        headers: { "Content-Type": "application/json" }
    })
        .then(res => {
            return res.json();
        })
        .then(data => {
            console.log(data);
            return data;
        });
};

【讨论】:

  • @A_Sk,看看这个!!
猜你喜欢
  • 2020-06-30
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 2019-04-22
  • 2019-10-21
  • 2019-07-23
相关资源
最近更新 更多