简体   繁体   English

用功能反应setState

[英]React setState with function

I am attempting to setState in a React component using a function callback which is now the recommended way. 我正在尝试使用函数回调在React组件中设置setState,这是现在推荐的方法。 It is in the componentDidMount and when I get my jobs data back I need to update the state. 它在componentDidMount中,当我取回工作数据时,我需要更新状态。 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 当您要基于prevState更新当前状态时,只需使用功能性setState,在这种情况下,您似乎只想设置状态作业,您只需编写

this.setState({jobs});

However if you want to use functional setState, you would still write 但是,如果要使用功能性setState,您仍然可以编写

  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 您需要通过从prevState获取值并将结果附加到先前的状态来更新作业,您可以这样做

async componentDidMount(){

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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