我有一个Ionic React应用程序,其中history.replace
用于在用户单击注销按钮时将用户从设置页重定向到登录屏幕。我希望能够在重定向中传递loggedOut
标志。然后,在“登录”页面上,我可以检查loggedOut
标志是否已设置并显示“您已注销”吐司消息。
这是带有注销按钮的设置页面代码
import React from 'react';
import { useHistory } from "react-router";
interface PageProps {
pageName: string | undefined;
}
const SettingsTab: React.FC<PageProps> = ({ pageName }) => {
console.log("render TabPage " + pageName);
const history = useHistory();
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonButtons slot="start">
<IonMenuButton />
</IonButtons>
<IonTitle>{pageName}</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<IonButton
onClick={async () => {
await logOut();
history.replace("/login");
//history.replace("/login", {loggedOut : "yes"});
}}
>
LOGOUT
</IonButton>
</IonContent>
</IonPage>
);
};
登录页面:
import React from "react";
import { RouteComponentProps } from "react-router";
const Login: React.FC<RouteComponentProps> = ({ history }) => {
// Check if loggedOut is set so we can display "You are logged out" message
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonButtons slot="start">
<IonMenuButton />
</IonButtons>
<IonTitle>Login Page {""}</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<IonButton
onClick={async () => {
await logIn();
history.replace("/dashboard");
}}
>
LOGIN
</IonButton>
</IonContent>
</IonPage>
);
};
我仍然是React的新用户,因此感谢您对此问题的任何帮助或建议。
答案 0 :(得分:1)
您可以使用localStorage
来存储和验证用户的身份验证状态,例如:
<IonButton
onClick={async () => {
await logIn();
localStorage.setItem("isLoggedIn", true);
history.replace("/dashboard");
}}
>
LOGIN
</IonButton>;
然后:
<IonButton
onClick={async () => {
await logOut();
localStorage.removeItem("isLoggedIn");
history.replace("/login");
}}
>
LOGOUT
</IonButton>;
要检查用户是否登录:
const isLoggedIn = localStorage.getItem("isLoggedIn") // returns true or false
答案 1 :(得分:1)
您可以在传递状态(标志)的同时导航到登录页面
history.replace("/login", {loggedOut : true});
然后在登录组件中,您可以像这样访问状态值: 已编辑
import React from "react";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
class Login extends React.Component {
render() {
const { match, location, history } = this.props;
const isLoggedOut = location.state && location.state.loggedOut
return (
<div>
<div>You are now at {location.pathname}</div>
{isLoggedOut ? <p>You have loggedout</p> : ''}
</div>;
)
}
}
export default withRouter(Login);