因此,我尝试按条件运行函数:如果我在catch
方法中遇到错误。
为此,我在组件状态下实现了this.state.loginError
,如果我们收到错误,它将在true
更改。所以,在error
之后 - this.state.loginError
与true
一起回来(这也是我在控制台中看到的.log(,但在状态更改后 - 我的函数loginError(target)
无论如何都不想启动。
请在下面查看我的代码和日志:
class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
navigate: false,
loginError: false,
}
}
handleSubmit = (e) => {
e.preventDefault();
axios.post('http://localhost:3016/auth/login', userLogin, {withCredentials: true})
.catch(err => {
this.setState({
loginError: true
});
console.log(this.state.loginError); // gives `true`
});
if (this.state.loginError) {
console.log('Error!') //does not work
loginError(target);
}
};
因为axios.post
是 asyc 函数,首先触发你的if
条件,然后.catch
钩子。要解决此问题,请尝试在其他地方替换您的条件,例如在 componentDidUpdate method
中。
componentDidUpdate() {
if (this.state.loginError) {
console.log('Error!') //does not work
loginError(target);
this.setState({ loginError: false });
}
}
检查这个: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_functio
您基本上是在尝试在仍未捕获错误时检查状态,因此状态没有更改。
如果将代码移动到 render 方法,您将看到它将起作用,因为它将在状态更改后重新呈现。或者,您可以使用componentDidUpdate
方法获得状态更改。
你为什么不试试Promises呢,这是非常清晰和简单的方法。
class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
navigate: false,
loginError: false,
}
}
handleSubmit = (e) => {
e.preventDefault();
return new Promise(resolve, reject){
axios.post('http://localhost:3016/auth/login', userLogin, {withCredentials: true})
.catch(err => {
reject(err);
})
.then(result => resolve(result));
}
//Else where in Your component use this promise, where ever you call it..
handleSubmit().then(// success code).error(// error code)
};
因为 axios.post
返回一个 promise,所以你之后编写的所有代码都将在 .then()
或 .catch()
语句之前执行。如果您需要在请求失败时调用loginError()
函数,您可以在.catch
语句中调用它:
axios.post('http://localhost:3016/auth/login', userLogin, {withCredentials: true})
.catch(err => {
loginError(target);
});
如果需要在更新状态后执行函数,可以使用setState
回调(第二个参数(:
axios.post('http://localhost:3016/auth/login', userLogin, {withCredentials: true})
.catch(err => {
this.setState({ loginError: true }, () => { loginError(target); })
});