React async await无法与功能组件一起工作



服务类方法:

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并转到其他部分,但当我调试代码时,我可以看到它从CCD_ 2方法。

您忘记了return logInUser中的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;
        });
};

最新更新