我正在遵循 Pluralsight 的初学者教程,在表单提交时将值传递给addUser
组件方法,我需要将 userName 推送到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
你打电话时{this.addUser}
,在这里被称为this
是你的类(组件)的一个实例,因此它不会给你带来错误,因为addUser
你的类中确实存在方法scope
,
但当你在addUser
你正在使用的方法this
更新state
其中存在于
类(组件)的范围,但目前你在addUser
方法,所以它会给你一个错误,如下所示addUser
范围你没有任何像状态、用户等的东西。
所以要解决这个问题你需要绑定this
当你打电话时addUser
方法。这样你的方法总是知道的实例this
.
因此,代码中的最终更改将如下所示:-
<Form addUser={this.addUser.bind(this)}/>
OR
You can bind
this
in the constructor,because it is the place when you should intialize things because constructor methods are called first when the components render to the
DOM
.
所以你可以这样做:-
constructor(props) {
super(props);
this.state = {
users: null
}
this.addUser=this.addUser.bind(this);
}
现在你可以像以前一样以正常方式调用它:-
<Form addUser={this.addUser}/>
我希望这会起作用,我已经向你明确说明了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)