反应 this.state 是未定义的?

新手上路,请多包涵

我正在关注 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 许可协议

阅读 747
2 个回答

当您调用 {this.addUser} 时,它会被调用,这里 this 是您的类(组件)的一个实例,因此它不会给您任何错误,因为 addUser does exist in your class scope , but when you are under addUser method you are using this to update the state which exist in the类(组件)的范围,但目前你在 addUser 方法的范围内,所以它会给你一个错误,如 addUser 范围你什么都没有像状态,用户等。所以要处理这个问题,你需要在调用 addUser 方法时绑定 this 。这样你的方法总是知道 this 的实例。

因此,您的代码的最终更改将如下所示:-

 <Form addUser={this.addUser.bind(this)}/>

或者


您可以在构造函数中绑定 this ,因为这是您应该初始化事物的地方,因为当组件渲染到 DOM 时,首先调用构造函数方法。

所以你可以这样做: -

   constructor(props) {
    super(props);
    this.state = {
        users: null
    }
    this.addUser=this.addUser.bind(this);
}

现在您可以像以前一样以正常方式调用它:-

 <Form addUser={this.addUser}/>

我希望这会奏效,而且我已经向你说清楚了。

原文由 Vinit Raj 发布,翻译遵循 CC BY-SA 3.0 许可协议

@Vinit Raj 的方法非常有效——尽管我更喜欢像这样使用箭头函数语法。

 <Form addUser={ () => this.addUser() }/>

使用这样的匿名函数,您不需要在任何地方绑定它。

原文由 Filtenborg 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Stack Overflow 翻译
子站问答
访问
宣传栏