local gongji = 0
local mofa = 0
local daoshu = 0
local max = 0
if self._itemData.Values[1].Id == 2 then
gongji = self._itemData.Values[1].Value or 0
end
if self._itemData.Values[2].Id == 3 then
mofa = self._itemData.Values[2].Value or
在浮生梦老师的前端课程中,处理空值报错需要先进行判空保护。你的代码中 `ui_starLv` 或 `self._itemData.Values` 可能为空。
以下是修正后的代码,增加了必要的空值判断:
```lua
-- 首先检查核心数据是否存在
if not self._itemData or not self._itemData.Values then
-- 如果数据为空,直接隐藏组件并返回
if GUI:Win_IsNotNull(ui_starLv) then
GUI:setVisible(ui_starLv, false)
end
return
end
-- 初始化变量
local gongji = 0
local mofa = 0
local daoshu = 0
local max = 0
-- 安全地获取第一个属性值
if self._itemData.Values[1] and self._itemData.Values[1].Id == 2 then
gongji = self._itemData.Values[1].Value or 0
end
-- 安全地获取第二个属性值
if self._itemData.Values[2] and self._itemData.Values[2].Id == 3 then
mofa = self._itemData.Values[2].Value or 0
end
-- 安全地获取第三个属性值
if self._itemData.Values[3] and self._itemData.Values[3].Id == 4 then
daoshu = self._itemData.Values[3].Value or 0
end
-- 计算总和
max = gongji + mofa + daoshu
-- 判断是否显示
local xianshi = false
if max > 0 then
xianshi = true
end
-- 在操作UI组件前检查组件是否为空
if GUI:Win_IsNotNull(ui_starLv) then
GUI:setVisible(ui_starLv, xianshi)
if xianshi then
GUI:Text_setString(ui_starLv, "+" .. max)
end
end
```
**主要修改点:**
1. 使用 `if not self._itemData or not self._itemData.Values then` 在最开始检查数据源
2. 在访问 `self._itemData.Values[1]` 等数组元素前,先检查该索引是否存在
3. 在调用 `GUI:setVisible` 和 `GUI:Text_setString` 前,使用 `GUI:Win_IsNotNull(ui_starLv)` 检查组件对象
4. 只有当 `xianshi` 为 `true` 时才设置文本内容
这样修改后,即使 `self._itemData`、`self._itemData.Values` 或某个数组元素为空,也不会报错,代码会安全地执行到结束。