【发布时间】:2017-09-01 10:57:25
【问题描述】:
我正在学习 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
【问题讨论】:
-
addUser = (userName) => { -
@Andrew 为什么要这样写?
-
用于自动绑定此函数中的上下文,但这里看起来不正确。
-
我知道 :p 只是我更喜欢 bind。它很脏但有效..
-
@IvanTopić 将此行放入构造函数中:
this. addUser = this. addUser.bind(this)该语法是属性初始化器语法,这是 实验性 语法,您需要为此使用 babel 插件。跨度>
标签: reactjs