我正在处理简单的react js应用程序,我正在验证用户,如果他/她已成功登录,我正在尝试重定向到主页,但我处于一些奇怪的情况。请帮我完成以下代码。
下面是函数fetchAPI
用一些输入参数调用服务器的代码
function fetchAPI(methodType, url, data, callback){
fetch(url,{
method: methodType,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => callback(data) )
.catch(error => callback(data));
}
现在我这样称呼它
fetchAPI("POST", Constants.LOGIN, data, function(callback) {
if(callback.status == 200) {
console.log(callback.message);
this.props.history.push("/home");
}else if( typeof callback.status != "undefined"){
alertModal("Alert", callback.message);
}
});
这样做的问题是它不会在响应条件中重定向到/home
但只打印成功消息。但是,当我直接使用fetch api时,如下面的代码,它将我重定向到/home
任何人都可以帮我解决为什么会发生这种情况?
fetch(Constants.LOGIN, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
if (data.status == 200) {
this.props.history.push("/home");
} else if (typeof data.status != "undefined") {
alertModal("Alert", data.message);
}
})
.catch(error => callback(data));
好吧,忘了回调,我去过那里,没有更多的CALLBACK HELL。
始终使用promises,您可以使用async / await简化所有内容:
async function fetchAPI(methodType, url, data){
try {
let result = await fetch(url, {
method: methodType,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}); // wait until request is done
let responseOK = response && response.ok;
if (responseOK) {
let data = await response.json();
// do something with data
return data;
} else {
return response;
}
} catch (error) {
// log your error, you can also return it to handle it in your calling function
}
}
在你的React组件中:
async someFunction(){
let result = await fetchAPI("POST", Constants.LOGIN, data); // wait for the fetch to complete
if (!result.error){
// get whatever you need from 'result'
this.props.history.push("/home");
} else {
// show error from 'result.error'
}
}
现在你的代码看起来更具可读性
fetch中的错误在result.error或result.statusText中,我很久以前停止使用fetch,切换到Axios。看看我对2 Here之间的一些差异的答案。
根据您的回应编辑
好的,根据您发布的代码:
import React from "react";
import Constants from "../Constants.jsx";
import { withRouter } from "react-router-dom";
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
errors: []
};
}
showValidationErr(elm, msg) {
this.setState(prevState => ({
errors: [...prevState.errors, { elm, msg }]
}));
}
clearValidationErr(elm) {
this.setState(prevState => {
let newArr = [];
for (let err of prevState.errors) {
if (elm != err.elm) {
newArr.push(err);
}
}
return { errors: newArr };
});
}
onEmailChange(e) {
this.setState({ email: e.target.value });
this.clearValidationErr("email");
}
onPasswordChange(e) {
this.setState({ password: e.target.value });
this.clearValidationErr("password");
}
submitLogin(e) {
e.preventDefault();
const { email, password } = this.state;
if (email == "") {
this.showValidationErr("email", "Email field cannot be empty");
}
if (password == "") {
this.showValidationErr("password", "Password field cannot be empty");
}
if (email != "" && password != "") {
var data = {
username: this.state.email,
password: this.state.password
};
// I added function keyword between the below line
async function someFunction(){
let result = await fetchAPI("POST", Constants.LOGIN, data); // wait for the fetch to complete
if (!result.error){
this.props.history.push("/home"); // Here is the error
} else {
// show error from 'result.error'
}
}
someFunction();
}
}
render() { ......................
####-----This is function definition------####
async function fetchAPI(methodType, url, data){
try {
let response = await fetch(url, {
method: methodType,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}); // wait until request is done
let responseOK = response && response.ok;
if (responseOK) {
let data = await response.json();
// do something with data
return data;
} else {
return response;
}
} catch (error) {
return error;
// log your error, you can also return it to handle it in your calling function
}
}
这是个想法,你应该让async
成为调用API的函数。在您的示例中,您的函数submitLogin
必须是异步的,因为它将调用内部的异步函数。只要你调用异步函数,调用者必须是异步的,或者相应地处理promise。这应该是这样的:
async submitLogin(e) {
e.preventDefault();
const { email, password } = this.state;
if (email == "") {
this.showValidationErr("email", "Email field cannot be empty");
}
if (password == "") {
this.showValidationErr("password", "Password field cannot be empty");
}
if (email != "" && password != "") {
var data = {
username: this.state.email,
password: this.state.password
};
let result = await fetchAPI("POST", Constants.LOGIN, data); // wait for the fetch to complete
if (!result.error) {
this.props.history.push("/home"); // Here is the error
} else {
// show error from 'result.error'
}
}
如果函数在构造函数中正确绑定,则this
不会有任何问题。看来你没有绑定构造函数中的submitLogin
函数,这会给你this
的上下文带来问题。这是它应该如何绑定:
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
errors: []
};
// bind all functions used in render
this.submitLogin = this.submitLogin.bind(this);
}
看看this article,了解this
背景下的问题。
现在,基于您提供的代码,在我看来您处于未知领域。如果你认为你发现路由很难或async / await不清楚,我建议你不要使用它们,并首先掌握React基础知识(你遇到的语法问题就是一个例子,你不应该有把那个功能放在那里,也与this
绑定问题)。
例如,请阅读this post,了解一般情况,并建议您在使用异步,提取或路由之前尝试其他更简单的示例。当您清除React生命周期后,您可以从那里继续,并使用异步功能,然后使用路由器。
我还建议您按照Official docs中的示例进行操作,并查看at this post以更好地理解async / await。
这些建议当然是为了让你掌握React的基本原理,并且将来基本没有任何问题! :)