我正在阅读《与Firebase反应之路》。 我想使用钩子为经过身份验证的用户提取会话处理:
const App = (props) => {
const [authUser, setAuthUser] = useState(null);
const firebase = useContext(FirebaseContext);
// cDM
useEffect(() => {
const listener = firebase.auth.onAuthStateChanged(authUser => {
authUser
? setAuthUser(authUser)
: setAuthUser(null)
});
return () => { listener() };
})
return (
<AuthUserContext.Provider value={authUser}>
<Router>
<div>
<Navigation />
<hr />
<Route exact path={ROUTES.LANDING} component={LandingPage} />
<Route path={ROUTES.SIGN_UP} component={SignUpPage} />
<Route path={ROUTES.SIGN_IN} component={SignInPage} />
<Route path={ROUTES.PASSWORD_FORGET} component={PasswordForgetPage} />
<Route path={ROUTES.HOME} component={HomePage} />
<Route path={ROUTES.ACCOUNT} component={AccountPage} />
<Route path={ROUTES.ADMIN} component={AdminPage} />
</div>
</Router>
</AuthUserContext.Provider>
);
}
我提取了更高阶的分量
const withAuthentication = Component => (props) => {
const [authUser, setAuthUser] = useState(null);
const firebase = useContext(FirebaseContext);
// cDM
useEffect(() => {
const listener = firebase.auth.onAuthStateChanged(authUser => {
authUser
? setAuthUser(authUser)
: setAuthUser(null)
});
return () => { listener() };
})
return (
<AuthUserContext.Provider value={authUser}>
<Component {...props} />
</AuthUserContext.Provider>
);
};
然后是
const App = () => (
<Router>
<div>
<Navigation />
<hr />
<Route exact path={ROUTES.LANDING} component={LandingPage} />
<Route path={ROUTES.SIGN_UP} component={SignUpPage} />
<Route path={ROUTES.SIGN_IN} component={SignInPage} />
<Route path={ROUTES.PASSWORD_FORGET} component={PasswordForgetPage} />
<Route path={ROUTES.HOME} component={HomePage} />
<Route path={ROUTES.ACCOUNT} component={AccountPage} />
<Route path={ROUTES.ADMIN} component={AdminPage} />
</div>
</Router>
);
export default withAuthentication(App);
带有身份验证的在我看来就像是包装纸。这是用钩子提取的正确方法吗? 具有钩子反应的高阶组件的合法用例吗?