ReactJS 保护路由和嵌套路由

ReactJS protected routes and nested routes

我在 ReactJS 的路线有问题。我定义了一些这样的路线:

...Import / Class...
class App extends Component {
    render() {
        return (
            <div>
                <Header />
                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/login" component={Login} />
                    <Route path="/signup" component={Signup} />
                    <ProtectedRoute path="/user/contact" component={Contact} />
                    <ProtectedRoute path="/user/person" component={UserPerson} />
                    <ProtectedRoute path="/user/profile" component={Profile} />
                    <Route component={NotFound} />
                </Switch>
                <Footer />
            </div>
        );
    }
}
...Export...

下面你可以看到我的ProtectedRouteclass

...Import / Class...
const ProtectedRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        AuthGestion.userIsAuthenticated() ? (
            <Component {...props} />
        ) : (
            <Redirect to={{
                pathname: '/login',
                state: { from: props.location }
            }}/>
        )
    )} />
);
...Export...

当我使用 <NavLink to="/user/person"></NavLink> 转到我的页面时,没有问题,我的组件已加载并且我可以看到我的页面。 但是当我直接进入url/user/person,并充值我的页面(CTRL + F5)时,我进入了Console错误SyntaxError: expected expression, got '<'和一个白页。 只是用户路由不起作用。

我在下面添加我的服务器信息:

import path from 'path';
import bodyParser from 'body-parser';
import express from 'express';
import mongoose from 'mongoose';
import routes from './routes/index.route';
import config from '../../config/config';

import webpack from 'webpack';
import webpackConfig from '../../config/webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

//Connexion MongoDB
mongoose.connect(config.mongodbUri, { useNewUrlParser: true });
mongoose.connection.on('connected', () => { console.log('MongoDB connecté'); });
mongoose.connection.on('error', (error) => { console.log(error); });

//Lancement serveur express
const server = express();

//Express need
server.use(bodyParser.json());
server.use(express.static(config.publicPath));
server.use(express.static(config.distPath));

//Hot reload
if(config.isDevMode) {
    const webpackCompiler = webpack(webpackConfig);
    server.use(webpackDevMiddleware(webpackCompiler, {}));
    server.use(webpackHotMiddleware(webpackCompiler));
}

// Route vers l'API
server.use('/api', routes);

// Landing page
server.get('/*', (req, res) => {
    res.sendFile(path.join(config.publicPath, '/index.html'));
});

//Ecoute du serveur
server.listen(config.port, () => {
    console.log(`App here : http://${config.host}:${config.port}`);
});

export default server;

你能帮我理解这个问题吗?如果它不好,也许可以更正我的路由。

供将来参考:

I've got a react/react-router page without any express and got the same error: SyntaxError: expected expression, got '<' which started to appear as soon as I configured a react route other then just root /.

After some experimenting I've figured out that in my index.html there was a link to js file:

So, the solution was to add / in the source path:

and the error has gone.

Hope that could help a bit.

自 React-Router 6.

以来已发生变化

您可以通过以下语法使用嵌套 routes/components。

import { Routes, Route, Navigate } from "react-router-dom";

function App() {
  return (
    <Routes>
      <Route path="/public" element={<PublicPage />} />
      <Route
        path="/protected"
        element={
          // Good! Do your composition here instead of wrapping <Route>.
          // This is really just inverting the wrapping, but it's a lot
          // more clear which components expect which props.
          <RequireAuth redirectTo="/login">
            <ProtectedPage />
          </RequireAuth>
        }
      />
    </Routes>
  );
}

function RequireAuth({ children, redirectTo }) {
  let isAuthenticated = getAuth();
  return isAuthenticated ? children : <Navigate to={redirectTo} />;
}