简体   繁体   English

反应setState不起作用

[英]React setState not working

I have the following constructor and function in a react component that I've created. 我创建的react组件中具有以下构造函数和函数。

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 未捕获的TypeError:无法读取未定义的属性'setState'

Can anyone help my identify the problem? 谁能帮助我确定问题所在?

In the following code, you use 'this', when you should be using 'self' 在下面的代码中,当您应该使用“ self”时,您使用“ this”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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