我没有使用组件做过更新,组件也会更新,当在返回jsx中使用受保护的私有路由时,我会向我显示错误,请帮助我,在另一个工作正常的模板中使用此代码
import React, { Component } from "react";
import firebase from "firebase";
import { Route, Redirect, Switch, BrowserRouter } from "react-router-dom";
import { firebaseInitialize } from "./views/Key/Config";
import "./App.scss";
const loading = () => (
<div className="animated fadeIn pt-3 text-center">Loading...</div>
);
//容器
const DefaultLayout = React.lazy(() => import("./containers/DefaultLayout"));
//页
const Login = React.lazy(() => import("./views/Pages/Login"));
const Register = React.lazy(() => import("./views/Pages/Register"));
const Page404 = React.lazy(() => import("./views/Pages/Page404"));
const Page500 = React.lazy(() => import("./views/Pages/Page500"));
class Routes extends Component {
constructor(props) {
super(props);
this.state = {
user: {}
};
}
//侦听器,用于登录或注销用户状态
componentDidMount() {
this.authListener();
}
componentWillMount() {
firebaseInitialize();
}
//设置用户登录状态
authListener() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.setState({ user });
} else {
this.setState({ user: null });
}
});
}
render() {
//if user loggedIn false redirect to landing "/"
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
this.state.user ? <Component {...props} /> : <Redirect to="/login"
/>
}
/>
);
//if user loggedIn true redirect to /dashboard
const ProtectedRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
!this.state.user ? (
<Component {...props} />
) : (
<Redirect to="/dashboard" />
)
}
/>
);
return (
<BrowserRouter>
<React.Suspense fallback={loading()}>
<Switch>
<PrivateRoute
exact
path="/login"
name="Login Page"
component={Login}
/>
<Route
exact
path="/register"
name="Register Page"
render={props => <Register {...props} />}
/>
<Route
exact
path="/404"
name="Page 404"
render={props => <Page404 {...props} />}
/>
<Route
exact
path="/500"
name="Page 500"
render={props => <Page500 {...props} />}
/>
<ProtectedRoute
path="/"
name="Home"
render={props => <DefaultLayout {...props} />}
/>
</Switch>
</React.Suspense>
</BrowserRouter>
);
}
}
导出默认路由;