简体   繁体   中英

Why am I getting a cannot read property props error for my function passed to a child?

So I have a button which updates an array stored in my back-end, I need that button to also update the state of my front-end with the new array from the back-end. I am passing a function which changes the state of the parent to the button but when I try to call that function with this.props.function() I get a TypeError: Cannot read property 'props' of undefined.

I have another button which uses basically the same code(except this one I call the passed function inside another function which I bind to onClick) and works perfectly fine so I am confused as to why this one is not working.

Parent:

//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}/>

Button

//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}

I can't seem to figure out whats wrong. I've been deleting and adding things for the last 2 hours. Help would be greatly appreciated:)

you also need to call bind on onCreateNewRoom

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

you could also use arrow functions to avoid re-binding this and this kind of mistakes:

onCreateNewRoom = () => {

So this inside of onCreateNewRoom will be bound to the class and not the onClick handler function.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

In the constructor this is bound to the class. When you call this.onCreateNewRoom.bind(this) you are setting this inside of the onCreateNewRoom to the value you pass as the first argument to bind . (Which is the this bound to the class and contains props ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM