小编典典

反应this.state是不确定的?

reactjs

我正在遵循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

阅读 273

收藏
2020-07-22

共1个答案

小编典典

当您调用时{this.addUser},它被调用,这this是您的类(组件)的一个实例,因此它不会给您任何错误,因为addUser方法确实存在于您的类中scope,但是当您处于addUser方法之下时,您将this用来更新state其中存在的方法。类(组件)的范围,但是当前您在addUser方法的范围内,因此它会给您带来错误,因为在addUserScope
下您没有像状态,用户等之类的东西。因此,要解决此问题,您需要this在调用时绑定addUser方法。这样您的方法就始终知道的实例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}/>

我希望这能奏效,并向您明确表示。

2020-07-22