简体   繁体   中英

React setState with function

I am attempting to setState in a React component using a function callback which is now the recommended way. It is in the componentDidMount and when I get my jobs data back I need to update the state. It works when I set it directly but I have attempted may functions callbacks and cannot get it to work. Sample code provided below with one of my many attempts.

async componentDidMount(){
    const jobs = await loadJobs();
    this.setState({jobs});
    //this.setState((prevState, jobs) =>  {return {jobs: [prevState,...jobs]}})
}

What is the correct syntax?

You only need to make use of functional setState when you want to update current state based on prevState, in your case it seems like you just want to set the state jobs, you would simply write

this.setState({jobs});

However if you want to use functional setState, you would still write

  this.setState((prevState) =>  {
     return {jobs};
  })

You need to update the jobs by getting value from prevState and appending the result to the previous state, you would do it like

async componentDidMount(){

    const jobs = await loadJobs();
    this.setState((prevState) =>  {
       return {jobs: [...prevState.jobs, ...jobs]}
    })

}

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