1.创建三个页面LoginPage, HomePage,NotFoundPage用于Router
创建LoginPage.tsx用于做登录页面
// LoginPage.tsx
const LoginPage = (props:LoginProp) => {const navigate = useNavigate();return( <h1 onClick={ ()=>{navigate("/");}}>Hello Login, {props.name}!</h1>)}export default LoginPage;//LoginMeta.tsxexport interface LoginProp extends MetaProp{}export interface LoginState extends MetaState{}
创建HomePage.tsx,作为主页面,登录完成后,会跳转到这个页面
// HomePage.tsx
const HomePage = (props: HomeProp)=> {const { name } = props; //解构赋值return (<div><h1>Hello, {name}!</h1></div>);}export default HomePage;
创建NotFoundPage.tsx ,作为其他路径页面,url是其他页面时,跳到这
// NotFoundPage.tsx
class NotFoundPage extends Component<MetaProp, MetaState> {constructor(props: LoginProp) {super(props);this.state = { count: 0 };}render() {return <h1>Hello, NotFound {this.props.name}!</h1>;}}export default NotFoundPage;
2.使用Context传递登录上下文
学习react-Provider解决props需要层层传递问题https://blog.csdn.net/jacklam200/article/details/140534994
在前面文章的基础上,给Global类添加用户信息用于判断是否登录
// Global.tsx
export class Global {constructor() {}type = "";count = 0;name = 'react';loading = true;userName = "";userToken = "";
}const globalStore = new Global();
export {globalStore};
3.定义AuthRouter用于判断登录
创建AuthRouter.tsx,利用之前讲到context,管理Global里的userToken数据
// AuthRouter.tsx
const AuthRouter = ({ children, redirectTo }) => {const theme = useTheme();// useEffect(// () => setUrlUser(username)// )return theme?.global?.userToken != null && theme?.global?.userToken != undefined && theme?.global?.userToken != "" ? children: <Navigate to={redirectTo} />;
}
export default AuthRouter;
4.配置Router
用AuthRouter配置需要登录页面,在这里我们只配置HomePage需要登录
// App.tsx
function App() {//const element = useRoutes(routes);return (<div className="App"><Routes><Route path="/" element={<AuthRouter redirectTo="/login"><HomePage name='test' /></AuthRouter>}/><Route path="login" element={<LoginPage name='login'/>} /><Route path="*" element={<NotFoundPage name='not found'/>} /></Routes> </div>);
}export default App;
5.测试页面
在登录页面,创建点击模拟登录
// LoginPage.tsx
const LoginPage = (props:LoginProp) => {const navigate = useNavigate();const theme = useTheme()return( <h1 onClick={ ()=>{setToken("1234")theme?.setGlobal({...theme?.global, "userToken":"1234"})navigate("/");}}>Hello Login, {props.name}!</h1>)}export default LoginPage;
这样只要没登录情况下,到HomePage页面,都会跳到LoginPage,直到登录,才真正到HomePage页面
另外需要持久化,可以用localStorage