javascript - 为什么我的函数传递给孩子时出现无法读取属性道具错误?
问题描述
所以我有一个按钮来更新存储在我的后端的数组,我需要这个按钮来更新我的前端的状态与来自后端的新数组。我正在传递一个将父级状态更改为按钮的函数,但是当我尝试使用 this.props.function() 调用该函数时,我得到一个 TypeError: Cannot read property 'props' of undefined。
我有另一个按钮,它使用基本相同的代码(除了这个我在绑定到 onClick 的另一个函数中调用传递的函数)并且工作得很好,所以我很困惑为什么这个不工作。
家长:
//within constructor
this.onUpdateRooms = this.onUpdateRooms.bind(this);
//function
onUpdateRooms(list) {
this.setState({roomList: list});
console.log(this.state.roomList);
}
//within render
<GenerateButton onUpdateRooms={this.onUpdateRooms}/>
按钮
//within the class declaration
constructor (props) {
super(props)
}
onCreateNewRoom() {
const newRoomCode = GenerateRandomCode.TextCode(6).toUpperCase();
console.log(newRoomCode);
let temp;
fetch('/api/newRoom', {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({roomCode: newRoomCode})
})
.then(res => res.json())
.then(list => temp=list);
this.props.onUpdateRooms(temp);
}
//then i set the button's onClick={this.onCreateNewRoom}
我似乎无法弄清楚出了什么问题。在过去的 2 个小时里,我一直在删除和添加内容。帮助将不胜感激:)
解决方案
你还需要bind
打电话onCreateNewRoom
constructor (props) {
super(props);
this.onCreateNewRoom = this.onCreateNewRoom.bind(this);
}
您还可以使用箭头函数来避免重新绑定this
和此类错误:
onCreateNewRoom = () => {
所以this
inside ofonCreateNewRoom
将绑定到类而不是onClick
处理函数。
bind() 方法创建一个新函数,在调用该函数时,将其 this 关键字设置为提供的值,并在调用新函数时提供的任何参数之前具有给定的参数序列。
在构造函数this
中绑定到类。当您调用时,this.onCreateNewRoom.bind(this)
您将this
在内部设置为onCreateNewRoom
您作为第一个参数传递给的值bind
。(这是this
绑定到类并包含props
)。
推荐阅读
- amazon-web-services - AWS Elastic Beanstalk Secrets Injection via .ebextension
- jquery - 有没有办法让我使用 jQuery 将会话变量发送到另一个页面?(顺便说一句,我正在使用 Laravel)
- python-3.x - 链表循环
- next.js - Next.js + AWS Amplify 授权标头
- javascript - 为什么 Angular 无法识别 jQuery 库
- sql - 我们可以使用 FOR JSON AUTO 在 SQL Server 中进行多重嵌套吗
- r - 嵌入到 R 的 gt 表的单元格的链接
- android - 将多个共享首选项键添加到鳍状肢共享首选项插件
- visual-studio - MSBuild“未找到 Windows SDK 版本 10.0.19041.0”,即使它已安装
- c++ - 为什么我们不能在一些 STL 容器中直接使用 lambdas 而不提及它的类型?