我使用 useAuth
挂钩进行身份验证,如 here 所述。我做了一个类似的钩子,如图所示:
const AuthContext = createContext();
export function ProvideAuth({children}) {
const auth = useProvideAuth();
return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>
}
export const useAuth = () => {
return useContext(AuthContext);
}
function useProvideAuth() {
const [user, setUser] = useState(null);
console.log(user); // originally prints 'null'
// after mounting and re-rendering prints USERNAME
const login = (username, password, callback, errorcb) => {
...
}
// A small diff here
useEffect(() => {
axios.get(
'/isLoggedIn/',
).then((response) => {
setUser(response.data.user)
}).catch(error => {
setUser(null)
})
}, [])
return {
user,
login,
}
}
在安装时,我调用 /isLoggedIn/
,并相应地更新状态,这应该会触发重新渲染。
但是我的 PrivateRoute
没有被重新渲染,所以 user
始终保持 null
并因此再次登录到登录页面。
function PrivateRoute({children, ...rest}) {
const auth = useAuth();
return (<Route {...rest}
render={({location}) => {
console.log(auth.user)
return auth.user ? (
children
) : (
<Redirect
to={{
pathname: '/login',
state: {from: location}
}}
/>
)
}}
></Route>)
}
我的App.js
function App() {
return (
<ProvideAuth>
<Router>
<Switch>
<PrivateRoute path="/builder">
<Builder/>
</PrivateRoute>
<Route path="/login">
<Login/>
</Route>
</Switch>
</Router>
</ProvideAuth>
)
}