typescript - 对象在回调中可能为 null
问题描述
我有以下代码:
let ctx = ref.current.getContext("2d");
if(ctx){
ctx.lineWidth=1; // here is ok!
ctx.strokeStyle=props.barStroke??"darkgray";// here is ok!
ctx.fillStyle=props.barFill??"blue"; // here is ok!
props.data.map((v,i)=>{
ctx.fillRect(i*10,0,10,props.height); //here it complain about ctx is possibly null!!
ctx.strokeRect(1*10,0,10,props.height);
})
}
我已经检查了 ctx ,所以 ctx.lineWidth 可以正常工作,但是在回调中,它表明该对象可能为空。如果我使用ctx?.method
代码无论如何都可以工作,那么在回调外部检查 null 的 ctx 怎么会在其中变成 null 呢?
这里有一个显示问题的链接。
解决方案
按照这个:
这是按预期工作的。类型检查器ctx
在创建回调函数时知道它是非空的,但在调用回调时它不知道它ctx
是非空的(因为 bar 是一个可变属性,可以在调用之前或调用之间更改回调函数)。
建议的方法是复制ctx
到 const local 然后在回调中使用它。
推荐阅读
- android - 在android中监控默认浏览器
- ios - 全局变量和静态变量对内存有害吗?
- xamarin.android - Xamarin.andriod 加载失败帮助我
- python - 如何在 Matplotlib 中围绕任意轴旋转 3-D 图
- mongodb - 在 mongoDB 中使用 replaceRoot
- javascript - 在 ReactNative 中更改 TextInput 的 fontFamily
- amazon-web-services - 通过 ebextension 更新 beanstalk 弹性负载均衡器
- asynchronous - useEffect() 导致 api 调用无限循环
- fork - Socat DTLS fork - 过度创建进程
- visual-studio - 获取 Flutter APK 文件