React Native自定义Hook报错:_readDb.useDisplayName不是函数
解决“_readDb.useDisplayName is not a function”报错
核心问题
你的自定义Hook useDisplayName 在 readDb.js 中是默认导出,但在 HomeScreen 里使用了命名导入(带花括号的语法),这导致React无法正确识别这个Hook,从而抛出函数不存在的错误。
分步解决方案
1. 修正导入语法
在 HomeScreen 中,将命名导入改为默认导入:
// 原代码(错误) import { useDisplayName } from "../../hooks/readDb"; // 修改后(正确) import useDisplayName from "../../hooks/readDb";
2. 修复用户为空的潜在报错
useAuth 返回的 user 在初始渲染时可能为 null,直接访问 user.uid 会引发报错,需要添加空值判断,同时完善依赖数组和错误捕获:
// 修改 readDb.js 中的 useDisplayName 函数 function useDisplayName() { const [displayName, setDisplayName] = useState(""); const { user } = useAuth(); useEffect(() => { // 用户未加载完成时直接返回 if (!user) return; get(child(ref(db), `users/${user.uid}`)) .then((snapshot) => { if (snapshot.exists()) { setDisplayName(snapshot.val().username); } else { console.log("No data available"); } }) .catch((error) => { // 捕获请求失败的错误,便于调试 console.error("获取用户名失败:", error); }); }, [user]); // 将 user 加入依赖数组,用户状态变化时重新获取数据 return displayName; }
3. 验证文件路径
确保 ../../hooks/readDb 的路径与你的项目文件结构完全匹配,避免因路径错误导致模块未找到的问题。
修改后的完整代码
readDb.js
import { db } from "../model/config"; import { get, ref, child } from "firebase/database"; import useAuth from "./useAuth"; import { useState, useEffect } from "react"; function useDisplayName() { const [displayName, setDisplayName] = useState(""); const { user } = useAuth(); useEffect(() => { if (!user) return; get(child(ref(db), `users/${user.uid}`)) .then((snapshot) => { if (snapshot.exists()) { setDisplayName(snapshot.val().username); } else { console.log("No data available"); } }) .catch((error) => { console.error("获取用户名失败:", error); }); }, [user]); return displayName; } export default useDisplayName;
HomeScreen.js
import { Button, Text, View } from "react-native"; import useAuth from "../../hooks/useAuth"; import { writeUserName } from "../../hooks/useWriteDb"; import useDisplayName from "../../hooks/readDb"; export default function HomeScreen(props) { const { signOut, user } = useAuth(); const name = useDisplayName(); return ( <View> <Text>{name || "加载中..."}</Text> </View> ); }
内容的提问来源于stack exchange,提问作者songexile9
相关产品推荐
相关产品推荐

