应该如何修复Typescript中的createContext错误(React TS Auth with Context



我应该如何修复createContext的问题?它期待一些争论,但我看不出有什么争论。我试着给它一些伪currentUser:undefined变量,它有点工作,但我不知道我应该如何处理其他defaultValue,如登录、注册等。它基于JS Auth教程,在JS中也工作,但我们希望它能在TSX上工作。提前感谢,下方的代码

AuthContext.tsx

const AuthContext = createContext()
export function useAuth() {
return useContext(AuthContext);
}
export default function AuthProvider( {children}:any ) {
const [currentUser, setCurrentUser] = useState();
function signup(email: string, password: string) {
return supabase.auth.signUp({
email: email,
password: password,
})
}
function login(email: string, password: string) {
return supabase.auth.signInWithPassword({
email: email,
password: password,
})
}
function logout() {
return supabase.auth.signOut()
}
function recoverPassword(email: string) {
return supabase.auth.resetPasswordForEmail(email);
}
function update(data: any) {
return supabase.auth.updateUser(data)
}
const value = {
currentUser, login, signup, logout, recoverPassword, update
}
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
}

创建一个接口,描述要存储在上下文中的数据:

interface AuthContextType {
currentUser: IUser;
login: (email: string, password: string) => ......,
signup: (email: string, password: string) => ....,
logout: () => void,
recoverPassword: (email: string) => ....,
update: (data: any) => ....
}

创建一个描述初始状态的对象:

const initialState = {
currentUser: null,
login: (email: string, ....) => console.error('No AuthProvider supplied. Wrap this component with a AuthProvider to use this functionality.'),
...
};

然后创建上下文:

const AuthContext = createContext<AuthContextType>(initialState);

您可以在中键入createContextYourInterface | null

const AuthContext = createContext<YourInterface|null>(null);

或者像在中那样键入一个空对象

const AuthContext = createContext({} as YourInterface)

最新更新