React+Firebase中安全检查auth.currentUser.email避免报错咨询
解决React中auth.currentUser.email未定义的报错问题
直接访问auth.currentUser.email会在auth.currentUser为null或undefined时抛出错误,因为无法读取空值的属性。要安全实现判断,需要先确保auth.currentUser存在,再检查其email是否与props.email匹配。
方案1:使用可选链操作符(推荐,简洁)
可选链?.会在左侧值为null/undefined时直接返回undefined,避免报错。结合逻辑与操作符&&,可以确保只有当auth.currentUser.email存在且匹配时才渲染按钮:
{auth.currentUser?.email && auth.currentUser.email === props.email ? ( <button onClick={() => deleteSchedule()} style={{ height: "3vh", width: "30%", backgroundColor: "black", color: "white" }}> Delete </button> ) : null}
方案2:嵌套条件判断(兼容老环境)
如果项目未配置支持ES2020+的可选链语法,可以用嵌套的条件判断逐步验证:
{auth.currentUser && auth.currentUser.email === props.email ? ( <button onClick={() => deleteSchedule()} style={{ height: "3vh", width: "30%", backgroundColor: "black", color: "white" }}> Delete </button> ) : null}
额外优化:处理auth加载状态
很多auth库(比如Firebase Auth)会有初始化加载阶段,此时auth.currentUser可能还未就绪。建议添加加载状态判断,避免组件渲染时的不确定性:
// 假设你有一个状态跟踪auth是否加载完成 const [authLoading, setAuthLoading] = useState(true); // 在组件初始化时监听auth状态变化 useEffect(() => { const unsubscribe = auth.onAuthStateChanged(user => { setAuthLoading(false); }); return unsubscribe; }, []); // 加载中时不渲染按钮相关逻辑 if (authLoading) { return null; // 也可以替换为加载动画组件 } return ( // 其他组件内容 {auth.currentUser?.email === props.email ? ( <button ...>Delete</button> ) : null} );
内容的提问来源于stack exchange,提问作者benpalmer
相关产品推荐
相关产品推荐

