【问题标题】:Setstate completes after even thou it's in a .then即使您在 .then 中,Setstate 也会完成
【发布时间】:2019-10-11 05:10:38
【问题描述】:

我对此感到非常困惑。我知道这与异步性质有关,但我无法让它按照我需要的方式运行。
我需要 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 之前解决

如何做到这一点?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    出于性能原因,React 批量状态更新。 在您设置为更新家庭的情况下,您可以使用本地范围的对象来获取中间结果

      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'
        })
      });
      })
    

    您也可以使用 async await 来解决这个问题,但这需要进行更多更改,

    希望对你有帮助

    【讨论】:

    • 这行不通,因为 updatedFamily 嵌套在 firebase 调用中没有?例如,当我 console.log 它是未定义的 @ibtsam
    • @FabricioG 我已经更新了我的答案以解决问题,请检查
    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多