反应 setState 不工作
React setState not working
我在我创建的 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
})
}
我在控制台中不断收到以下错误:
Uncaught TypeError: Cannot read property 'setState' of undefined
谁能帮我找出问题所在?
在下面的代码中,您使用了 '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
})
我在我创建的 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
})
}
我在控制台中不断收到以下错误:
Uncaught TypeError: Cannot read property 'setState' of undefined
谁能帮我找出问题所在?
在下面的代码中,您使用了 '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
})