tôi đang theo một hướng dẫn người mới bắt đầu từ Pluralsight, vào mẫu nộp một giá trị được truyền cho addUser
phương pháp thành phần và tôi cần phải đẩy userName để this.state.users
nhưng tôi nhận được lỗiPhản ứng this.state là không xác định?
App.jsx:14 Uncaught TypeError: Cannot read property 'users' of undefined
Component
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
'addUser = (userName) => {' – Andrew
@Andrew Tại sao bạn cần viết theo cách đó? –
Để tự động nhập ngữ cảnh trong chức năng này, nhưng có vẻ như không chính xác ở đây. – Andrew