在我的表格中,我执行以下操作
import useReactRouter from 'use-react-router';
const { history } = useReactRouter();
onSubmit={async (values, { setSubmitting }) => {
setSubmitting(true);
fetch('/register', {
method: 'POST',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(async response => {
setSubmitting(false);
if (!response.success) return showAlert();
await login();
history.push('/profile');
})
登录这样做:
export const AuthContext = createContext<any>(null);
const AuthProvider = ({ children }: ProviderProps): JSX.Element => {
const [auth, setAuth] = useState({
isAuthenticated: false,
user: null
});
const login = () => {
fetch('/me')
.then(res => res.json())
.then(response => {
if (response) setAuth({ isAuthenticated: true, user: response });
});
};
const logout = () => {
fetch('/logout').then(() =>
setAuth({ isAuthenticated: false, user: null })
);
};
return (
<AuthContext.Provider
value={{
state: {
auth
},
actions: {
login,
logout
}
}}
>
{children}
</AuthContext.Provider>
);
};
注册后,`isAuthenticated 在下面的代码中返回true,但导航到另一个页面后又返回false,可能是什么问题?
const PrivateRoute = (props: PrivateRouteProps) => {
const { component: Component, ...rest } = props;
const {
state: {
auth: { isAuthenticated }
}
} = useContext(AuthContext);
console.log(isAuthenticated);
<Router>
<div>
<AuthProvider>
<Header />
<Route exact path="/" component={Home} />
<MuiPickersUtilsProvider utils={LocalizedUtils} locale={nlLocale}>
<Route exact path="/register" component={Register} />
</MuiPickersUtilsProvider>
<PrivateRoute exact path="/profile" component={Profile} />
</AuthProvider>
</div>
</Router>
我正在寻找一种解决方案来在登录所有页面后保持 isAuthenticated 状态,即使在单击另一个链接或调用 history.push 之后
忽然笑
HUWWW
相关分类