React Native出现null is not an object (evaluating 'str.split')报错如何修复
问题修复方案
报错根因
你触发报错的原因是 auth?.currentUser?.displayName 返回了null值:可选链只会阻断undefined/null属性调用的报错,只会把最终str赋值为null,后续直接对null调用split方法就会触发null is not an object的报错。
另外出现displayName为null通常有两个常见原因:
- 注册用户时没有完成
displayName的赋值就提前跳转到了HomeScreen,Firebase新创建的用户默认displayName就是null,需要主动调用接口赋值 - HomeScreen首次渲染时,Firebase的auth状态还没初始化完成,
currentUser暂时为null
修复步骤
1. 加基础容错逻辑(必改)
先对str加兜底默认值,避免空值调用方法报错,同时对拆分后的结果也加兜底,避免异常时展示空白:
// 原有代码替换为以下内容 const str = auth?.currentUser?.displayName || ''; const welcomeText = str.split(' ')[0] || '访客';
改完后至少不会再触发页面崩溃,异常情况会默认展示「访客」作为用户名。
2. 检查注册流程的赋值逻辑
确认你注册用户的逻辑里,是等待displayName设置完成之后再跳转HomeScreen,示例参考:
import { getAuth, createUserWithEmailAndPassword, updateProfile } from "firebase/auth"; const auth = getAuth(); // 注册逻辑示例 createUserWithEmailAndPassword(auth, 邮箱, 密码) .then((userCredential) => { const user = userCredential.user; // 给用户设置displayName return updateProfile(user, { displayName: '用户输入的完整用户名' }); }) .then(() => { // 必须等displayName设置成功后再跳转HomeScreen,否则跳转后拿到的还是null navigation.replace('Home'); })
3. 补充auth状态监听(可选,解决初始化延迟问题)
如果改完上面两步还是偶现空值,说明是Firebase auth初始化慢的问题,可以加状态监听等auth加载完成后再渲染内容:
import { useEffect, useState } from 'react'; import { View, Text, Image, StyleSheet } from 'react-native'; import { auth } from '../firebase'; const HomeScreen = ({ navigation }) => { const [welcomeText, setWelcomeText] = useState('访客'); const [loading, setLoading] = useState(true); useEffect(() => { // 监听auth状态变化 const unsubscribe = auth.onAuthStateChanged(user => { if (user) { const name = user.displayName || ''; setWelcomeText(name.split(' ')[0] || '访客'); } setLoading(false); }) // 组件卸载时取消监听 return unsubscribe; }, []) // 加载中展示占位 if (loading) return <Text>加载中...</Text> return ( // 原有渲染逻辑不变 <View style={styles.homeContainer}> <View style={styles.overviewContainer}> <View style={styles.welcomeContainer}> <Text style={styles.welcomeText}>Hello <Text style={styles.welcomeTextBold}>{welcomeText}</Text></Text> <Image style={styles.welcomeIcon} source={require('../assets/images/Welcome-Icon.png')} /> </View> </View> </View> ) }
内容的提问来源于stack exchange,提问作者Mitchell G
相关产品推荐
相关产品推荐

