You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用useSelector解构数据时如何检查Null避免报错?

解决useSelector解构时的Null/Undefined检查问题

报错原因是state.vehicles或state.vehicles.data为null/undefined,直接嵌套解构会触发类型错误。你可以在解构的每一层嵌套设置默认空对象来避免这个问题:

const {
  vehicles: {
    data: { reminderVehicles } = {}, // 当data为null/undefined时,使用默认空对象兜底
  } = {}, // 当vehicles为null/undefined时,使用默认空对象兜底
} = useSelector((state) => state);

这样即使上层数据未加载完成或为null,解构过程也不会抛出错误,reminderVehicles会被赋值为undefined(而非触发报错)。

另外,在后续使用reminderVehicles时,建议保留可选链操作符进一步做防御性处理:

document.getElementById("VehicleRegistration").value = `${
  (prepopVehicleReg && reminderVehicles?.[0]?.Registration) || ""
}`;

内容的提问来源于stack exchange,提问作者Bomber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:27:36