Javascript 反应为什么此.state不能正确更新?

Javascript 反应为什么此.state不能正确更新?,javascript,reactjs,promise,axios,Javascript,Reactjs,Promise,Axios,因此,我尝试按条件运行函数:如果我在catch方法中出错 为此,我在组件状态中实现了this.state.loginError,如果出现错误,它将在true上更改。因此,在error之后,this.state.loginError返回true(这也是我在console.log中看到的),但在状态更改之后,我的函数loginError(target)无论如何都不想启动 请参阅下面的我的代码和日志: class LoginPage extends Component { constructo

因此,我尝试按条件运行函数:如果我在
catch
方法中出错

为此,我在组件状态中实现了
this.state.loginError
,如果出现错误,它将在
true
上更改。因此,在
error
之后,
this.state.loginError
返回
true
(这也是我在console.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函数,首先在
条件下触发
,然后在
之后触发
钩子。要修复此问题,请尝试在其他位置替换您的条件,例如在
componentdiddupdate方法中

componentDidUpdate() {
 if (this.state.loginError) {
    console.log('Error!') //does not work
    loginError(target);
    this.setState({ loginError: false });
   }
}
选中此项:

您基本上是在错误仍未捕获时尝试检查状态,因此状态没有更改


如果将代码移动到render方法,您将看到它将工作,因为它将在状态更改后重新渲染。或者您可以使用
componentdiddupdate
方法更改状态。

为什么不尝试使用Promissions,这是一种非常简单明了的方法

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
返回一个承诺,所以在它之后编写的所有代码都将在
.then()
.catch()
语句之前执行。如果需要在请求失败时调用
loginError()
函数,可以在
语句中调用它

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); })
    });