【问题标题】:React state doesn't get updated using produceReact 状态不会使用 produce 得到更新
【发布时间】:2022-11-17 20:22:10
【问题描述】:

我有一个复杂的状态 calculationResults 作为

export interface ICalculationResult {
hw: IHwCalculationResult;
}

export interface IHwCalculationResult {
header: IHwCalculationResultHeader;
agreements: IAgreementItem[];
}

export interface IAgreementItem {   
agreementRows: IAgreementRow[];
}

我想从 calculationResults.hw.agreements 中删除与产品相关的协议,然后推送从 api 收到的 agreements

我正在使用 immer,因为对象有很多属性,记录数将超过 5000

 const nextState = produce(calculatedResults,(draftstate: any) =>{
      if(allsite == "1"){      
        var indices: any = [];            
        draftstate.hw.agreements.forEach(function(value:any,pos: number){
          if(value.boQItem.id == productNo)
          {
            indices.push(pos);
          }
        });
          for(var index = indices.length-1;index>=0;index--)
          {
            draftstate.hw.agreements.splice(indices[index],1);
          }   
          draftstate.hw.agreements.push(...data.hw.agreements);   
        
        }
    });

我需要将状态设置为setCalculationResults(newState)吗?但是当我这样做的时候,有一个编译器错误,newState is incompatible for calculationResults

【问题讨论】:

  • 像这样做。 setCalculationResults(produce((draft) => {....})。在这里您可以直接对草稿进行更改。您可以按照此示例了解如何将 immer 与 React 结合使用。 React & Immer
  • @Mohammed Nouman Rafique 我按照建议修改了代码。但是我得到错误,无法读取未定义的属性(读取'hw')

标签: reactjs react-state immer.js


【解决方案1】:

根据@Muhammad Nouman Rafique,我厌倦了在setCalculationResults 中使用producer,但抛出了错误cannot read properties of undefined(reading 'hw')。 在这种情况下,produce 方法无法找到草稿的初始状态。因此它变为空并抛出错误。 语法似乎比文档所说的有所改变。所以这就是我如何不可变地更新状态。

 setCalculationResults(produce(draft =>{},calculationResults));

所以我的整体代码如下所示,

if(allsite == "1"){  
setCalculationResults(produce((draftstate: any) =>{              
var indices: any = [];            
draftstate.hw.agreements.forEach(function(value:any,pos: number){
   if(value.boQItem.id == productNo)
   {
   indices.push(pos);
   }
  });
  for(var index = indices.length-1;index>=0;index--)
  {                
   draftstate.hw.agreements.splice(indices[index],1);
  }              
   draftstate.hw.agreements.push(...data.hw.agreements);            
  },calculationResults));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-29
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多