【问题标题】:How to fix the error object is possibly null or undefined using react and typescript?如何使用 react 和 typescript 修复错误对象可能为 null 或未定义?
【发布时间】:2022-01-03 07:36:45
【问题描述】:

您好,当我登录到浏览器控制台时,我有如下数据,

data **** {progressValue: {...}}

如下所示

progress {
    completed: "10",
    total: "20",
}

我想检查完成的值是否大于或等于总值然后停止轮询。

下面是代码,

I have defined progress type for query like so 

type progress {
    completed: String
    total: String 
}  

async Progress(id: 
    QueryCheckArgs['id']) {
        const { data } = await this.get(
        `/${BASE_PATH}/${id}/progress/`
        );
        const output = {
            completed: data.connectivity_test_completed_if,
            total: data.connectivity_test_total_if,
        }; 
        return output;
    }


const Component = () => {
     const {
         data: progressValue,
         startPolling: startPolling,
     } = useProgress({
         variables: { id },
         fetchPolicy: 'network-only',
     });
     if (progressValue) {
         if (progressValue.progress.completed >= 
         progressValue.progress.total) { //error here says object 
         //is 
    //possibly null or undefined
         setProgress(undefined);
         stopPolling();
     }
  }

}

我怎样才能重写上面的条件,使得错误对象可能是未定义的或 null 是固定的。现在应该是什么类型的进展谢谢。

【问题讨论】:

  • 共享接口或您接收的数据类型?
  • 我已经分享了当我登录浏览器控制台和展开数据时数据的外观。我不知道它的类型。还是个初学者。

标签: reactjs typescript


【解决方案1】:

由于您尚未定义任何数据类型,因此请尝试使用Object Chaining:

if (progressValue?.progress?.completed >= progressValue?.progress?.total)

【讨论】:

  • 表示已完成且查询中不存在总类型
猜你喜欢
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 2021-12-29
  • 1970-01-01
  • 2020-05-11
相关资源
最近更新 更多