setState is not updating state properly

后端 未结 4 1955
忘掉有多难
忘掉有多难 2021-01-21 09:31

Sorry, I really miss something with the transmission of state within props of sub components in React.

I have implemented a version of a todo l

4条回答
  •  太阳男子
    2021-01-21 09:59

    The problem is from Array.push return the number of elements in the array and not the updated array

    addTask(task) {
      this.setState({
        tasks: this.state.tasks.push(task)
      })
    }
    

    To fix this you can push to state.tasks then setState with it later on:

    addTask(task) {
      this.state.tasks.push(task);
      this.setState({
        tasks: this.state.tasks
      })
    }
    

    This way you set state.task to the updated array.

提交回复
热议问题