简体   繁体   中英

setState does not update array state in React Js

I try to get value from the input and put it into object then push to new array. Then combine this array(with setState) with my state array. However, my state array value always returns empty. Could you please say where is the mistake. Thanks.

class AddExtraSeassion extends Component {
  constructor(props) {
    super(props);

    this.checkValidity = this.checkValidity.bind(this);
    this.onChangeDate = this.onChangeDate.bind(this);
    this.onChangeTime = this.onChangeTime.bind(this);
    this.onChangeDuration = this.onChangeDuration.bind(this);

    this.state = {
      checkedStudentLength: 0,
      validity: false,
      seassionDuration: null,
      seassionDate: null,
      seassionTime: null,
      showSeassion: false,
      seassions: []

    }
  }


  addSeassion = () => {
    this.setState({showSeassion: true});
  }

  onChangeDate = (event) => {
    this.setState({seassionDate: event.target.value});
  };
  onChangeTime = (event) => {
    this.setState({seassionTime: event.target.value});
  };
  onChangeDuration = (event) => {
    this.setState({seassionDuration: event.target.value});
  };

  checkValidity() {
    const seassionDate = this.state.seassionDate;
    const seassionTime = this.state.seassionTime;
    const seassionDuration = this.state.seassionDuration;

    const obj = {
      "Date": seassionDate,
      "Time": seassionTime,
      "Duration": seassionDuration
    };
    let SeassionList=[];

    SeassionList.push(obj);
    console.log(JSON.stringify(SeassionList) + " SeassionList array"); // print result
    this.setState({
      seassions: [...this.state.seassions, SeassionList]
    })
    console.log(JSON.stringify(this.state.seassions) + " state array"); // always empty

As @norbitrial mentioned setState is async operation so console.log() will not show the updated state. If you want to check if the state is updating or not you can use the callback provided by the setState method like below:

this.setState(prevState => ({
      seassions: [...prevState.seassions, SeassionList[0]]
    }),() => {
    console.log(this.state.seassions);
})

The first thing is you should not expect to see the changes in that line of console.log() immediately after your usage of setState() because it is asynchronous action.

Also you can try using the previous state of you array and passing obj instead of SeassionList :

this.setState(prevState => ({
   ...prevState,
   seassions: [...prevState.seassions, obj]
}))

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