-1

I'm using Reactjs 16.10.2 to make Website. But I can't setState.

First I passed function as a props of a component:

  getStepFour = (data)=>{

      this.setState({
        tenCaThi:data.tenCaThi,
        ngayThi:data.ngayThi,
        gioBatDau:data.gioBatDau,
        gioKetKetThuc:data.gioKetKetThuc,
        phongThi:data.phongThi,
      });

      console.log('data receipt four: ', data);
      console.log('state after set: ', this.state.tenCaThi);
    }
<ChiaCaThi getStepFour={this.getStepFour}/>

Then I used it to get data in ChiaCathi like this:

componentWillUnmount = ()=>{

          const data = {
            tenCaThi:this.state.tenCaThi,
            ngayThi:this.state.ngayThi,
            gioBatDau:this.state.gioBatDau,
            gioKetKetThuc:this.state.gioKetKetThuc,
            phongThi:this.state.phongThi,
          }

          console.log('data in chiacathi: ', data)

          this.props.getStepFour(data);
      }

For some setState was not working. State after set is null.

imghttps://i.stack.imgur.com/AAhdD.png

quanchinhong
  • 142
  • 3
  • 18

1 Answers1

2

That is because setState() is asynchronous. According to the React documentation for state,

setState() does not always immediately update the component. It may batch or defer the update until later.

Furthermore,

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

If you wish to read more about why state isn't updated immediately, feel free to read this, it is pretty in depth when it comes to explaining it.

wentjun
  • 40,384
  • 10
  • 95
  • 107