[英]React context with undefined default value Type Checking
只是想找出鍵入檢查 React Context 的正確方法是什么。 這就是我在我的上下文中所擁有的:
import React, { useContext } from "react";
import { UserAuth } from "../../types";
interface Props {
children: React.ReactChild;
}
interface IAuthContext {
currentUser: UserAuth;
setCurrentUser: React.Dispatch<React.SetStateAction<UserAuth>>;
}
const defaultUser: UserAuth = {
userId: "",
idToken: "",
timestamp: "",
authenticated: false,
};
const AuthContext = React.createContext<IAuthContext | null>(null);
const AuthProvider = ({ children }: Props) => {
const [currentUser, setCurrentUser] = React.useState<UserAuth>(defaultUser);
return (
<AuthContext.Provider value={{ currentUser, setCurrentUser }}>
{children}
</AuthContext.Provider>
);
};
const useAuthContext = () => {
const data = useContext(AuthContext);
if (data === null) {
throw new Error("This hook should be used inside SomeAppComponent");
}
return data;
};
export { AuthProvider, useAuthContext };
然后我用提供者包裝我的 App 組件:
ReactDOM.render(
<React.StrictMode>
<AuthProvider>
<ThemeProvider theme={defaultTheme}>
<GlobalStyle />
<ToastContainer />
<App />
</ThemeProvider>
</AuthProvider>
</React.StrictMode>,
document.getElementById("root")
);
最后在我的 App 組件中,我嘗試像這樣使用上下文:
export const App: FC = () => {
const { currentUser, setCurrentUser } = useAuthContext();
console.log(currentUser);
return (
<Router>
<Switch>
<Route exact path="/signup" component={SignUp} />
<Route exact path="/login" component={LogIn} />
<Route exact path="/" component={Dashboard} />
<Route exact path="/dashboard" component={Dashboard} />
</Switch>
</Router>
);
};
像這樣,我的應用程序拋出了我提供的錯誤:“throw new Error("This hook should be used inside SomeAppComponent");”
什么是正確的方法?
我像這樣編輯了我的代碼:
interface IAuthContext {
currentUser: UserAuth;
setCurrentUser: React.Dispatch<React.SetStateAction<UserAuth>> | null;
}
const defaultUser: UserAuth = {
userId: "",
idToken: "",
timestamp: "",
authenticated: false,
};
const AuthContext = React.createContext<IAuthContext>({
currentUser: defaultUser,
setCurrentUser: null,
});
它有效,但我覺得這不是正確的方法,有什么幫助嗎? 謝謝,F。
是的,我認為您的初始解決方案是更好的方法。
我在這里重現它並且它運行良好而不會引發錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.