0

我在我创建的反应组件中有以下构造函数和函数。

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

我在控制台中不断收到以下错误:

未捕获的类型错误:无法读取未定义的属性“setState”

谁能帮我找出问题?

4

1 回答 1

3

在下面的代码中,你使用 'this',而你应该使用 'self'

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

应该

catch(function(error) {
    self.setState({error: error}) // Error points to this line
})
于 2016-10-27T14:41:33.190 回答