我将大多数应用程序包装在上下文提供程序中,以存储与身份验证相关的值,这在大多数情况下都可以正常工作。但是,当我刷新需要身份验证的页面时,在上下文提供程序中设置的状态会重置自身并触发我的一系列重定向(基于未获得授权的用户)。在页面刷新后,是否仍要保留上下文提供者的状态?
基本上我的app.js
return
块看起来像这样:
<AuthContextProvider>
<Switch>
<Route exact path="/main" render={(props) => <Main />} />
<Route
exact
path="/login"
render={(props) => <LoginRoutes {...props} />}
/>
<Route
exact
path="/user-dashboard"
render={(props) => <UserDashboardRoutes {...props} />}
/>
</Switch>
</AuthContextProvider>
AuthContextProvider
如下所示:
const AuthContextProvider = (props) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [name, setName] = useState("");
const [client, setClient] = useState();
const setAuth = (boolean) => {
setIsAuthenticated(boolean);
};
const apiVerifyOptions = {
url: "users/is-verified",
method: "GET",
headers: {
token: localStorage.token,
},
};
const apiUserOptions = {
url: "users/user",
method: "GET",
headers: {
token: localStorage.token,
},
};
function getUser() {
axios(apiUserOptions)
.then((response) => {
const resData = response.data;
setName(resData.username);
setClient(resData.client_id);
console.log(resData);
})
.catch((error) => {
console.log(error.response);
});
}
function isAuth() {
axios(apiVerifyOptions)
.then((response) => {
const resData = response.data;
if (resData === true) {
console.log("Is logged in");
getUser();
setIsAuthenticated(true);
} else {
console.log("Is not logged in");
setIsAuthenticated(false);
}
})
.catch((error) => {
console.log(error.response);
});
}
useEffect(() => {
isAuth();
}, []);
return (
<AuthContext.Provider
value={{ isAuthenticated, setIsAuthenticated, setAuth, name, client }}
>
{props.children}
</AuthContext.Provider>
);
};
export default AuthContextProvider;
处理重定向的组件如下所示:
function UserDashboardRoutes(props) {
const { isAuthenticated, setAuth } = useContext(AuthContext);
console.log(isAuthenticated);
return isAuthenticated ? (
<UserDashboard {...props} setAuth={setAuth} />
) : (
<Redirect to="/login" />
);
}
export default UserDashboardRoutes;