Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 要在for循环中设置状态对象:React+;打字稿_Reactjs_Typescript_Setstate - Fatal编程技术网

Reactjs 要在for循环中设置状态对象:React+;打字稿

Reactjs 要在for循环中设置状态对象:React+;打字稿,reactjs,typescript,setstate,Reactjs,Typescript,Setstate,我有一个状态对象,它基本上是一个对象数组。我正在执行一个fetch调用,它返回的对象数组应该设置为state对象。但我不能这样做。 还有别的选择吗? 我哪里做错了 我们将不胜感激 this.state = { accounts: [{firstname:"",lastname:"",age:"",id:""}], }; async componentDidMount(){ let useraccounts = await this.fetchAccounts();

我有一个状态对象,它基本上是一个对象数组。我正在执行一个fetch调用,它返回的对象数组应该设置为state对象。但我不能这样做。 还有别的选择吗? 我哪里做错了

我们将不胜感激

 this.state = {
      accounts: [{firstname:"",lastname:"",age:"",id:""}],
 };

 async componentDidMount(){

   let useraccounts =  await this.fetchAccounts();
   if(useraccounts.length > 0)
     { 
       for(let i=0;i<useraccounts.length;i++)
        {
            account = {firstname:useraccounts[i].firstname,lastname:useraccounts[i].lastname,age:useraccounts[i].age,id:useraccounts[i].id}; 
            this.setState((prevState) => ({  accounts: [ ...prevState.accounts, account ]}));            
        }                   
     }  
 }

 fetchAccounts = async() => {

    //fetch API call which will return all users accounts

 }
this.state={
帐户:[{firstname:,lastname:,年龄:,id:}],
};
异步组件didmount(){
让useraccounts=等待这个。fetchAccounts();
如果(useraccounts.length>0)
{ 
for(设i=0;i({accounts:[…prevState.accounts,account]}));
}                   
}  
}
fetchAccounts=async()=>{
//获取将返回所有用户帐户的API调用
}

您不需要单独为每个帐户调用
setState
,只需对所有帐户进行一次调用:

async componentDidMount(){
  try {
    let useraccounts =  await this.fetchAccounts();
    let newAccounts = useraccounts.map(({firstname, lastname, age, id}) => ({firstname, lastname, age, id}));
    this.setState(({accounts}) => ({accounts: [...accounts, ...newAccounts]}));
  } catch (e) {
    // Do something with the error
  }
}
它获取帐户,创建一个只包含相关属性的新数组(您在
for
循环中执行的操作),然后调用
setState
添加新帐户

请注意,我正在
map
回调和
setState
回调的参数列表中进行解构,以仅挑出它们接收到的我想要的部分对象。例如:

let newAccounts = useraccounts.map(({firstname, lastname, age, id}) => ({firstname, lastname, age, id}));
与此相同:

let newAccounts = useraccounts.map(account => {
  return {
    firstname: account.firstname,
    lastname: account.lastname,
    age: account.age,
    id: account.id
  };
});
只是更简洁一点

当然,如果您真的不需要复制对象,您可以直接使用从
fetchAccounts
获得的帐户:

async componentDidMount(){
  try {
    let useraccounts =  await this.fetchAccounts();
    this.setState(({accounts}) => ({accounts: [...accounts, ...useraccounts]}));
  } catch (e) {
    // Do something with the error
  }
}

关于原始代码的一些注释:

  • 使用
    async
    函数时,任何东西都不会处理它返回的承诺,这违反了承诺的规则之一:您需要处理发生的任何错误,而不是忽略它们。这就是为什么我添加了一个
    try
    /
    catch

  • 如果您正在执行for(让i=0;我在循环中首先准备数组,然后只执行一次setState。如下所示:
    let arr=[];for(让i=0;i({accounts:[…prevState.accounts,arr]}));