首页 > 解决方案 > React Typescript - 变量空检查被忽略并发送错误

问题描述

Javascript新手在这里^^

在我的 React 前面,我有以下 chrome 错误消息:

Unhandled Rejection (TypeError): Cannot read property 'style' of null

▶ 2 stack frames were collapsed.

new LiquidFillGauge

SOMEPATH/liquidFillGauge.tsx:46

  43 | var gauge = d3.select('#' + elementId);
  44 | var radius = 0, locationX = 0, locationY = 0;
  45 | if (gauge != null && gauge != undefined) {
> 46 |     radius = Math.min(parseInt(gauge.style('width')), parseInt(gauge.style('height'))) / 2;
  47 | ^   locationX = parseInt(gauge.style('width')) / 2 - radius;
  48 |     locationY = parseInt(gauge.style('height')) / 2 - radius;
  49 | }

Gauge 在第 45 行被过度检查,它在第 46 行仍然显示为空。

为什么会这样?我怎样才能避免错误?

谢谢

标签: reactjstypescript

解决方案


做就是了

if(gauge){
   radius = Math.min(parseInt(gauge.style('width')), parseInt(gauge.style('height'))) / 2; 
   locationX = parseInt(gauge.style('width')) / 2 - radius;
   locationY = parseInt(gauge.style('height')) / 2 - radius;
}

在 javascript 或 typescript 中,null 或 undefined 返回 false。


推荐阅读