反应异步等待不使用功能组件
React async await not working with function component
服务class方法:
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 并转到其他部分但是当我调试代码时我可以看到它正在返回数据
logInUser
方法。
您忘记了 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;
});
};
服务class方法:
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 并转到其他部分但是当我调试代码时我可以看到它正在返回数据
logInUser
方法。
您忘记了 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;
});
};