Reactjs 反应状态不工作

Reactjs 反应状态不工作,reactjs,ecmascript-6,typeerror,setstate,Reactjs,Ecmascript 6,Typeerror,Setstate,在我创建的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

在我创建的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
    })
}
我在控制台中不断收到以下错误:

未捕获的TypeError:无法读取未定义的属性“setState”


有人能帮我找出问题吗?

在下面的代码中,您应该使用“self”时使用“this”

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

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

在下面的代码中,当您应该使用“self”时,使用“this”

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

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

您还可以使用一个箭头函数,然后
这个
将继承
handleSubmit的词法范围
谢谢,这很有效!我还必须使用user
error:error.message
,但这超出了我的范围question@ken4z我该如何完成呢?
catch((error)=>this.setState({error:error.message}))
。不过,您必须设置一些东西来传输代码,因为并非所有浏览器都支持该功能。巴别塔是一个流行的选择。考虑到你在问这个问题,我建议按照上面的答案去做,因为它不需要构建步骤。啊,好的。对不起,这是个糟糕的假设!幸运的是,你还可以使用箭头函数,然后
这个
将继承
handleSubmit的词法范围
谢谢,这很有效!我还必须使用user
error:error.message
,但这超出了我的范围question@ken4z我该如何完成呢?
catch((error)=>this.setState({error:error.message}))
。不过,您必须设置一些东西来传输代码,因为并非所有浏览器都支持该功能。巴别塔是一个流行的选择。考虑到你在问这个问题,我建议按照上面的答案去做,因为它不需要构建步骤。啊,好的。对不起,这是个糟糕的假设!好运气您需要使用
refs
来获取值吗?如果组件是
输入
元素,则可以使用
onChange
事件并使用该值更新变量。在
refs
上使用该组件是否有好处?当您无法根据文档对事件、状态或道具执行相同操作时,refs应该是最后的选择。此外,当使用浅层渲染进行单元测试时,浅层渲染也不起作用。我没有意识到这一点,我将研究更改浅层渲染以获得更好的实践,谢谢:)您需要使用
refs
来获取值吗?如果组件是
输入
元素,则可以使用
onChange
事件并使用该值更新变量。在
refs
上使用该组件是否有好处?当您无法根据文档对事件、状态或道具执行相同操作时,refs应该是最后的选择。此外,当使用浅层渲染进行单元测试时,浅层渲染也不起作用。我没有意识到这一点,我将研究如何更改浅层渲染以获得更好的实践,谢谢:)