首页 > 解决方案 > setState 没有被触发

问题描述

我有以下代码

 setTimeout(() => {
        this.setState({loading: true});
    }, 0);
   axos.post("....")

setState 由于某种原因没有被触发。有人可以帮忙吗?

这是代码

submit(ev) {
    ev.preventDefault();

    setTimeout(() => {
        this.setState({loading: true});
    }, 0);

    const {email, password} = ev.target.elements;

  app.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);
    // As httpOnly cookies are to be used, do not persist any state client side.
    app.auth().signInWithEmailAndPassword(email, password).then(user => {
        // Get the user's ID token as it is needed to exchange for a session cookie.
        app.auth().onAuthStateChanged((user) => {
            if (user) {
                this.setState({loading: true});
                return user.getIdToken().then(idToken => {
                    // Session login endpoint is queried and the session cookie is set.
                    // CSRF protection should be taken into account.
                    const csrfToken = Utils.getCookie('csrfToken');
                    return this.postIdTokenToSessionLogin('/auth/session-login', idToken, csrfToken, "auth");
                });
            } else {
                this.setState({error: "There was an error", loading: false});
            }
        });
    }).catch(error => {
        this.setState({error: error.message, loading: false});
    })
}

标签: reactjs

解决方案


使用时,class methods我们应该首先使用bind它们constructor。这与thisjavascript 中的工作方式有关。this从内部访问时,submit它实际上是指submit而不是您的Component. 要么bind这样

class Foo extends React.Component{
    constructor(props){
        super(props)
        this.submit = this.submit.bind(this)
    }

    submit(e){
        //now this refers to Foo's instance
    }
}

或者你可以使用arrow functionswhich has alexical this

class Foo extends React.Component{
    submit = e =>{
        //here this already refers to Foo's instance
    }
}

推荐阅读