类型错误:无法读取 null 的属性(读取“uid”)

问题描述 投票:0回答:1

我需要运行该挂钩来获取具有 currentUser.uid 名称的文档,但它失败了。该钩子在我获取 currentUser 之前启动,所以基本上它在 currentUser 为空时启动。我也无法理解这种行为。

TypeError:无法读取 null 的属性(读取“uid”) 来源 src/layout/SideBar/index.tsx (29:22) @ SideBar

背景:

export const AuthContextProvider = ({ children }: { children: ReactNode }) => {
  const [currentUser, setCurrentUser] = useState<any>(null);

  useEffect(() => {
    const unsub = onAuthStateChanged(
      auth,
      (user) => user && setCurrentUser(user)
    );

    return () => unsub();
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
};

成分:

export const SideBar = () => {
  const { currentUser } = useContext(AuthContext);

  useEffect(() => {
    const unsub = onSnapshot(doc(db, "userChats", currentUser.uid), (doc) => {
      setUserChats(doc.data());
      setLoading(false);
    });

    return () => unsub();
  }, [currentUser.uid]);


  return (
  ...
  );
};

reactjs react-hooks react-context
1个回答
0
投票

我想你问的是如何更新Sidebar中的UseEffect以免出错?

如果是这种情况,则会出错,因为尝试调用

currentUser
OnSnapshot

为空

要解决此问题,您只需检查

currentUser
中是否不为 null 或未定义
useEffect
:

 useEffect(() => {
    if(currentUser !== null && currentUser !== undefined)
    {  
      const unsub = onSnapshot(doc(db, "userChats", currentUser.uid), (doc) => {
              setUserChats(doc.data());
              setLoading(false);
            });
        
      return () => unsub();
    }
  }, [currentUser.uid]);
© www.soinside.com 2019 - 2024. All rights reserved.