最佳答案
我遵循一个来自 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