reactjs - 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 行仍然显示为空。
为什么会这样?我怎样才能避免错误?
谢谢
解决方案
做就是了
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。
推荐阅读
- java - 如何创建一个在每个元音后添加破折号的方法?
- python - 在 Python 中的 Paramiko 中强制密码身份验证(忽略 .ssh 文件夹中的密钥)
- c# - 如何使用 Rhino 在基类中模拟受保护的方法?
- php - 在远程服务器上安装 Symfony
- java - 如何使二叉搜索树成为Java中的完整二叉搜索树?
- java - this.packagename 在 Android Studio 中不起作用?
- core-plot - barFillForPlotColor 的核心绘图快速版本
- powerbi - power bi 矩阵中的自定义聚合列
- java - 调用存储在 ArrayList 中的对象的方法时出错
- python - 使用 python 仅在 R(Red) 通道中显示图像