React Native添加Firebase竞赛条目报route.params.id未定义错误
报错原因
这个错误本质是取值时访问了undefined对象的属性,具体触发原因有两个:
- 你通过路由跳转到
AddEntry页面时,没有在导航参数中传入id字段,导致route.params本身为undefined,直接读取route.params.id就会抛出类型错误 - 代码存在命名冲突风险:组件本身命名为
AddEntry,组件内部定义的提交函数也叫AddEntry,会引发作用域覆盖,就算参数问题修复也可能触发函数调用异常
修复步骤
- 修正页面跳转逻辑,跳转进入AddEntry页面时必须传入对应竞赛id:
// 其他页面跳转到新增条目页的正确写法 navigation.navigate('AddEntry', { id: "这里替换为你需要关联的Firebase竞赛文档ID" }) - 修改AddEntry组件代码,增加参数兜底逻辑,同时解决命名冲突问题:
const AddEntry = ({route, navigation}) => { // 用可选链+默认值做兜底,避免参数缺失时直接报错 const id = route?.params?.id ?? '' const [title, onChangeTitle] = React.useState('') const [image, setImage] = React.useState("/") const pickImage = async () => { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); console.log(result); if (!result.cancelled) { setImage(result.uri); } }; // 内部提交函数改名,避免和组件名重名 const handleSubmitEntry = async() => { // 提交前校验id是否存在,避免无效请求 if (!id) { console.warn('未获取到关联竞赛ID,无法提交') return } let imageUrl = await handleImageUpload() addEntryToComp({title, imageUrl}, id) } return( <View> <Text>Add Entry</Text> <Text>{id}</Text> <Button title='Upload Entry Image' color="red" onPress={pickImage}></Button> {/* 绑定改名后的提交函数 */} <Button title='Save' color="purple" onPress={handleSubmitEntry}></Button> </View> ) } export default AddEntry - 如果使用了嵌套导航结构,确认跳转AddEntry时的导航实例属于对应路由栈,避免跨栈跳转导致参数丢失。
内容的提问来源于stack exchange,提问作者Jeandré De Villiers
相关产品推荐
相关产品推荐

