Setstate即使在.then中也可以完成

时间:2019-10-11 05:10:38

标签: reactjs

我对此很困惑。我知道它与异步性质有关,但我无法使其按我需要的方式起作用。
我需要firebase.set才能运行。完成后,将运行this.setstate,一旦完成,将运行下一个。

    .then(keyUid => {
      let updatedFamily = {...family, [keyUid]: [firstHousehold, lastHousehold, householdDropdown]};

      this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + keyUid ).set(
        {
            first: firstHousehold,
            last: lastHousehold,
            phone: phone,
            email: email,
            address: address,
            address2: address2,
            city: city,
            zip: zip,
            headOfHousehold: headOfHousehold,
          }, (error) => {
               if(error){
                  console.log(error);
               }
               else{
                    this.setState({ family: updatedFamily }, () => console.log(1));
                }
        })
    })
    .then(newHouseholdUid => {
      console.log(2);
      Object.keys(family).forEach(key => {
        this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + key ).update({
          family: 'howdly'
        })
      });
  })

当前,console.log(2)在console.log(1)之前运行。我希望this.setstate在继续到下一个.then

之前先解决。

如何实现?

1 个答案:

答案 0 :(得分:1)

出于性能原因,反应批次状态更新。 如果您将状态设置为updatedFammily,则可以使用本地范围的对象来获取中间结果

  let res = {}
  ...


    .then(keyUid => {
  let updatedFamily = {...family, [keyUid]: [firstHousehold, lastHousehold, householdDropdown]};
  res.updatedFamily = updatedFamily;

  this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + keyUid ).set(
    {
        first: firstHousehold,
        last: lastHousehold,
        phone: phone,
        email: email,
        address: address,
        address2: address2,
        city: city,
        zip: zip,
        headOfHousehold: headOfHousehold,
      }, (error) => {
           if(error){
              console.log(error);
           }
           else{
                this.setState({ family: updatedFamily }, () => console.log(1));
            }
    })
})
.then(() => {
  console.log(2);
  Object.keys(res.updatedFamily).forEach(key => {
    this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + 
   key ).update({
      family: 'howdly'
    })
  });
  })

您还可以使用异步等待来解决此问题,但这需要进行更多更改,

希望有帮助