我一直在研究 React js 并希望 setState
以获取来自 firebase 的响应。
因此,当我尝试为状态设置值时,它会返回错误,
Cannot read property 'setState' of undefined
我的代码。
class Login extends Component {
constructor(props) {
super(props)
this.state = {email:'',
uid:'',
password :'',
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.signInWithGoogle = this.signInWithGoogle.bind(this)
}
handleChange(event) {
this.setState({
[event.target.id] : event.target.value
})
console.log(this.state.email)
console.log(this.state.password)
}
handleSubmit(e) {
e.preventDefault()
firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(result) {
console.log(result.user.uid)
this.setState({ [uid]: [result.user.uid] });
}).catch(function(error) {
console.log(error.code)
console.log(error.message)
alert(error.message)
})
}
我确实有一个表格可以提供输入。 有人可以帮我解决这个问题吗。
最佳答案
请像这样更新您的 handleSubmit 函数
handleSubmit(e) {
e.preventDefault()
firebase.auth().signInWithEmailAndPassword(this.state.email,
this.state.password).then((result) => {
console.log(result.user.uid)
this.setState({ uid: result.user.uid });
}).catch(function(error) {
console.log(error.code)
console.log(error.message)
alert(error.message)
})
}
此作用域仅在粗箭头函数 () => {} 内可用,所以我刚刚更新了您的函数
firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(result) {
到
firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((result) => {
关于javascript - 即使在定义绑定(bind)后也无法读取未定义的属性 'setState'(this.submit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387385/