首页 > 解决方案 > 为什么我的函数传递给孩子时出现无法读取属性道具错误?

问题描述

所以我有一个按钮来更新存储在我的后端的数组,我需要这个按钮来更新我的前端的状态与来自后端的新数组。我正在传递一个将父级状态更改为按钮的函数,但是当我尝试使用 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 个小时里,我一直在删除和添加内容。帮助将不胜感激:)

标签: javascriptreactjsjsx

解决方案


你还需要bind打电话onCreateNewRoom

constructor (props) {
        super(props);
    this.onCreateNewRoom = this.onCreateNewRoom.bind(this);
    }

您还可以使用箭头函数来避免重新绑定this和此类错误:

onCreateNewRoom = () => {

所以thisinside ofonCreateNewRoom将绑定到类而不是onClick处理函数。

bind() 方法创建一个新函数,在调用该函数时,将其 this 关键字设置为提供的值,并在调用新函数时提供的任何参数之前具有给定的参数序列。

在构造函数this中绑定到类。当您调用时,this.onCreateNewRoom.bind(this)您将this在内部设置为onCreateNewRoom您作为第一个参数传递给的值bind。(这是this绑定到类并包含props)。


推荐阅读