gpt4 book ai didi

reactjs - React this.state 未定义?

转载 作者:行者123 更新时间:2023-12-03 12:56:20 25 4
gpt4 key购买 nike

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

最佳答案

当您调用 {this.addUser} 时,它会被调用,这里 this 是您的类(组件)的实例,因此它不会给您带来错误因为 addUser 方法确实存在于您的类 scope 中,但是当您使用 addUser 方法时,您正在使用 this 来更新存在于中的 state类(组件)的范围,但当前您位于 addUser 方法的范围内,因此它会给您一个错误,如在 addUser 范围下,您没有得到任何类似状态、用户的信息ETC。因此,要解决这个问题,您需要在调用 addUser 方法时绑定(bind) this,以便您的方法始终知道 this 的实例。

所以代码中的最终更改将如下所示:-

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


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

所以你可以这样做:-

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

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

<Form addUser={this.addUser}/>

我希望这会起作用,我已经向你明确说明了。

关于reactjs - React this.state 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45998744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com