简体   繁体   中英

React setState not working

I have the following constructor and function in a react component that I've created.

constructor() {
    super()
    this.state = {
        error: false
    }
}

handleSubmit(e) {
    e.preventDefault()
    const email = this.refs.email.value
    const password = this.refs.password.value
    const self = this

    firebase.auth().signInWithEmailAndPassword(email, password).then(
        function(result) {
            const location = self.props.location
            if (location.state && location.state.nextPathname) {
                self.context.router.replace(location.state.nextPathname)
            } else {
                self.context.router.replace("/home")
            }
            // User signed in!
            console.log("User signed in!")
    }).catch(function(error) {
        this.setState({error: error}) // Error points to this line
    })
}

I keep getting the following error in the console:

Uncaught TypeError: Cannot read property 'setState' of undefined

Can anyone help my identify the problem?

In the following code, you use 'this', when you should be using 'self'

catch(function(error) {
    this.setState({error: error}) // Error points to this line
})

should be

catch(function(error) {
    self.setState({error: error}) // Error points to this line
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM