我对打字稿非常陌生,并将我的react应用迁移到使用ts。
我正在使用firebase auth服务,并且遇到了一些似乎无法解决的类型问题。请指教!
import React, { useEffect, useState } from 'react';
import app from './firebase';
export const AuthContext = React.createContext(null);
export const AuthProvider: React.FC<Props> = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [pending, setPending] = useState(true);
useEffect(() => {
app.auth().onAuthStateChanged((user) => {
// ts error here
setCurrentUser(user);
setPending(false);
});
}, []);
if(pending){
return <>Loading...</>;
}
return (
<AuthContext.Provider
// ts error here
value={{ currentUser }}
>
{children}
</AuthContext.Provider>
);
};
interface Props {
children: React.ReactNode;
}
setCurrentUser(user);
给我一个错误
Argument of type 'User | null' is not assignable to parameter of type 'SetStateAction<null>'.
和
value={{ currentUser }}
给我一个错误Type '{ currentUser: null; }' is not assignable to type 'null'.
答案 0 :(得分:1)
从firebase返回的用户参数,其类型不能分配为null,因此您应为此用途创建类型或接口,或者可以尝试添加“ any”,如下所示:
const [currentUser, setCurrentUser] = useState<any>(null);
答案 1 :(得分:0)
对我来说,我添加到上下文中并且它起作用了
export const AuthContext = createContext<any>(null)