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

删除对象数组最后一个元素时出现"Cannot read property 'title'"错误求助

问题:删除最后一个收藏项时出现"Cannot read property 'title' of undefined"错误

我的应用包含一个收藏项选择列表,用户选中的项会通过以下代码添加到对象数组:

dispatch(
  addFavorite({
    id: currentIndex,
    title: getIds[currentIndex].title,
    liked: 'true',
  }),
);

删除数组最后一个对象时会报错"Cannot read property 'title' of undefined",但删除其他对象无异常。例如我的数组结构如下:

selectedFavorites: [
  {
    title: '',
    id: '',
    liked: '',
  },
  {
   title: 'First Title',
   id: 1,
   liked: true,
  },
  {
   title: 'Second Title',
   id: 2,
   liked: true,
  },
],

现有代码逻辑

Redux中用filter方法删除元素:

removeFavorite: (state, action) => {
  return {
    ...state,
    selectedFavorites: state.selectedFavorites.filter(
      fav => fav.id !== action.payload,
    ),
  };
},

触发删除的函数:

const handlePress = () => {
  dispatch(removeFavorite(getFavoriteTitles[currentIndex].id));
};

渲染收藏项的代码:

const getFavoriteTitles = getFavorites.selectedFavorites.map((f, index) => {
    return f;
  });

return (
       <View>
        <Text>            
          {getFavoriteTitles[currentIndex].title}
        </Text> 
       </View>
        )

我尝试过多种条件渲染检查,比如:

if (
    getFavorites.selectedFavorites.some(
      el => el.id === getFavoriteTitles[currentIndex].id,
    )
    // getFavoriteTitles.length
    // getFavoriteTitles.length > 0
    // getFavoriteTitles[favoriteIndex].title.length > 0
  ) {
    return (
      <SafeAreaView style={lightGlobalStyles.flex}>
          <Animated.View>
            <Text
              style={[
                style.favoritesText,
                theme.theme === true
                  ? themes.whiteText
                  : theme.theme2 === true
                  ? themes.yellowText
                  : theme.theme5 === true
                  ? themes.darkText
                  : themes.offWhiteText,
              ]}>
              {getFavoriteTitles[currentIndex].title}
            </Text>
          </Animated.View>
        <Background />
      </SafeAreaView>
    );
  } else {
    return (
      <SafeAreaView style={lightGlobalStyles.flex}>
        <View>
          <Text
            style={[
              style.favoritesText,
              theme.theme === true
                ? themes.whiteText
                : theme.theme2 === true
                ? themes.yellowText
                : theme.theme5 === true
                ? themes.darkText
                : themes.offWhiteText,
            ]}>
            No favorites selected
          </Text>
        </View>
        <Background />
      </SafeAreaView>
    );
  }

问题原因及解决办法

核心原因

删除最后一个有效项后,currentIndex的数值没有同步更新,导致它超出了新数组的索引范围,此时getFavoriteTitles[currentIndex]变成undefined,访问其title属性就会报错。另外初始数组里的空对象也会干扰索引判断。

具体修复步骤

  1. 清理初始数组
    把初始的selectedFavorites改成空数组,去掉无用的空对象:
// Redux初始state修改为
selectedFavorites: []
  1. 同步更新currentIndex
    删除项后,检查当前索引是否超出新数组的范围,及时调整:
// 假设currentIndex是用useState管理的,修改handlePress函数
const handlePress = () => {
  const targetId = getFavoriteTitles[currentIndex].id;
  dispatch(removeFavorite(targetId));
  // 删除后如果当前索引是最后一个,调整为新数组的最后有效索引
  if (currentIndex >= getFavoriteTitles.length - 1) {
    setCurrentIndex(prev => Math.max(0, prev - 1));
  }
};
  1. 渲染时增加安全校验
    不要直接访问getFavoriteTitles[currentIndex].title,先判断对象是否存在:
// 简化渲染逻辑,去掉多余的map
const getFavoriteTitles = getFavorites.selectedFavorites;

return (
  <View>
    <Text>            
      {getFavoriteTitles[currentIndex] ? getFavoriteTitles[currentIndex].title : 'No favorites selected'}
    </Text> 
  </View>
)
  1. 优化条件渲染判断
    先判断数组是否有有效项,再进行后续操作:
if (getFavoriteTitles.length > 0 && getFavoriteTitles[currentIndex]) {
  // 渲染收藏项
} else {
  // 渲染无收藏提示
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:34:55