我正在关注 Pluralsight 的初学者教程,在表单上提交一个值传递给 addUser
组件方法,我需要将用户名推送到 this.state.users
但我收到错误
App.jsx:14 Uncaught TypeError: Cannot read property 'users' of undefined
零件
import React from 'react'
import User from 'user'
import Form from 'form'
class Component extends React.Component {
constructor() {
super()
this.state = {
users: null
}
}
// This is triggered on form submit in different component
addUser(userName) {
console.log(userName) // correctly gives String
console.log(this.state) // this is undefined
console.log(this.state.users) // this is the error
// and so this code doesn't work
/*this.setState({
users: this.state.users.concat(userName)
})*/
}
render() {
return (
<div>
<Form addUser={this.addUser}/>
</div>
)
}
}
export default Component
原文由 Ivan Topić 发布,翻译遵循 CC BY-SA 4.0 许可协议
当您调用
{this.addUser}
时,它会被调用,这里this
是您的类(组件)的一个实例,因此它不会给您任何错误,因为addUser
does exist in your classscope
, but when you are underaddUser
method you are usingthis
to update thestate
which exist in the类(组件)的范围,但目前你在addUser
方法的范围内,所以它会给你一个错误,如addUser
范围你什么都没有像状态,用户等。所以要处理这个问题,你需要在调用addUser
方法时绑定this
。这样你的方法总是知道this
的实例。因此,您的代码的最终更改将如下所示:-
或者
您可以在构造函数中绑定
this
,因为这是您应该初始化事物的地方,因为当组件渲染到DOM
时,首先调用构造函数方法。所以你可以这样做: -
现在您可以像以前一样以正常方式调用它:-
我希望这会奏效,而且我已经向你说清楚了。