【发布时间】: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