为了使React类组件在登录后保持其状态,并根据组件中当前可用的状态更改可用路由,可以采取以下步骤:
AuthContext
。这个上下文可以包含用户登录状态、用户信息等相关数据。AuthContext.Provider
将上下文提供给整个应用程序。AuthContext.Consumer
来访问上下文中的用户登录状态和用户信息。<Route>
组件的render
属性或component
属性来渲染不同的组件或重定向到不同的路由。以下是一个示例代码:
// AuthContext.js
import React from 'react';
const AuthContext = React.createContext();
export default AuthContext;
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import AuthContext from './AuthContext';
import PrivateRoute from './PrivateRoute';
import LoginPage from './LoginPage';
import HomePage from './HomePage';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
user: null,
};
}
handleLogin = (user) => {
this.setState({
isLoggedIn: true,
user: user,
});
}
handleLogout = () => {
this.setState({
isLoggedIn: false,
user: null,
});
}
render() {
return (
<AuthContext.Provider value={{
isLoggedIn: this.state.isLoggedIn,
user: this.state.user,
login: this.handleLogin,
logout: this.handleLogout,
}}>
<Router>
<Route exact path="/login" component={LoginPage} />
<PrivateRoute exact path="/home" component={HomePage} />
<Route exact path="/">
{this.state.isLoggedIn ? <Redirect to="/home" /> : <Redirect to="/login" />}
</Route>
</Router>
</AuthContext.Provider>
);
}
}
export default App;
// PrivateRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import AuthContext from './AuthContext';
const PrivateRoute = ({ component: Component, ...rest }) => (
<AuthContext.Consumer>
{({ isLoggedIn }) => (
<Route
{...rest}
render={(props) =>
isLoggedIn ? <Component {...props} /> : <Redirect to="/login" />
}
/>
)}
</AuthContext.Consumer>
);
export default PrivateRoute;
// LoginPage.js
import React from 'react';
import AuthContext from './AuthContext';
class LoginPage extends React.Component {
static contextType = AuthContext;
handleLogin = () => {
// Perform login logic
const user = { name: 'John' };
this.context.login(user);
}
render() {
return (
<div>
<h1>Login Page</h1>
<button onClick={this.handleLogin}>Login</button>
</div>
);
}
}
export default LoginPage;
// HomePage.js
import React from 'react';
import AuthContext from './AuthContext';
class HomePage extends React.Component {
static contextType = AuthContext;
handleLogout = () => {
// Perform logout logic
this.context.logout();
}
render() {
return (
<div>
<h1>Welcome, {this.context.user.name}!</h1>
<button onClick={this.handleLogout}>Logout</button>
</div>
);
}
}
export default HomePage;
在上述示例中,AuthContext
用于管理用户登录状态和用户信息。App
组件作为根组件,使用AuthContext.Provider
提供上下文。PrivateRoute
组件用于保护私有路由,只有在用户已登录时才能访问。LoginPage
组件用于登录,成功登录后更新上下文中的用户登录状态和用户信息。HomePage
组件用于展示已登录用户的欢迎信息,并提供注销功能。
请注意,上述示例中的代码仅为演示目的,实际应用中可能需要根据具体需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云