React Native iOS模拟器运行出现names.slice相关TypeError报错求解
问题根因
错误触发的核心原因是ModuleSelect组件首次渲染时,从Redux中取出的state.entities.game.distinctnames值为undefined,对undefined调用slice方法直接抛出类型错误。
出现这个问题的常见原因有两个:
- 你在
navigation focus的副作用中才执行dispatch(loadProgress())加载数据,该副作用执行时机晚于组件首次渲染,首次渲染时数据还没更新到Redux中 - 你的
gameReducer没有给distinctnames、distinctmodules设置初始空数组的默认值,或者Redux中存储的字段名和你useSelector里写的字段名拼写不一致
修复步骤
1. 给gameReducer设置正确的初始值
找到你的gameReducer文件,在初始state中给用到的列表字段设置默认空数组:
// 示例:gameReducer的初始state定义 const initialState = { // 原有其他字段保留 currentModule: null, currentScenario: null, completedmodules: [], distinctmodules: [], // 新增默认空数组 distinctnames: [], // 新增默认空数组 // 其他原有字段保留 }
2. 组件调用方法前加兜底判断
修改ModuleSelect组件中调用slice的两行代码,加上空值兜底,避免值异常时报错:
// 把原来的两行替换成下面的代码 let dnames = (names ?? []).slice(current_index, current_index + 4); let dmodules = (modules ?? []).slice(current_index, current_index + 4);
3. 可选校验字段拼写
检查gameReducer中存储的字段名是否和useSelector中读取的完全一致,比如是否有大小写差异(比如是不是把distinctNames写成了distinctnames)。
内容的提问来源于stack exchange,提问作者Patel01
相关产品推荐
相关产品推荐

