使用react-router-dom添加额外页面

问题描述 投票:0回答:2

目前,我只有一个主页(/)。现在,我想添加带有另一个路径(/about)的附加页面,因此我尝试包含反应路由器。

当我在 index.js 中执行此操作时,它有效:

const Home = () => {
  return (
  <HomePage></HomePage>
  );
};

export default Home;

但是当我这样做时:

import HomePage from './HomePage';
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

const Home = () => {
  return (
  <Router>
    <Switch>
      <Route exact path="/" component={HomePage} />
    </Switch>
  </Router>
  );
};

export default Home;

我在本地主机上收到此错误:

Server Error
ReferenceError: document is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

我也在index.js中尝试过这个:

const Home = () => {
  if (typeof document !== 'undefined') {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={HomePage} />
        </Switch>
      </Router>
    );
  } else {
    // Handle server-side rendering (optional)
    return null;
  }
};

但随后我会收到此错误:

Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Home`.

我错过了什么?

javascript html reactjs dom nestjs
2个回答
0
投票

您的代码片段似乎正在尝试使用 React Router 对 React 应用程序进行服务器端渲染(SSR)。但是,这种方法存在一些问题:

  1. 服务器端渲染通常涉及不同的技术和设置,包括将 Next.js 等库用于 React 应用程序。
  2. React Router 通常不直接用于服务器端渲染,因为它主要是一个客户端路由库。 下面是一个简化的示例,说明如何使用不同的方法通过 React 处理服务器端渲染:

// In your server-side rendering code (e.g., using Node.js and Express)
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import App from './App'; // Your main application component

// Express route handler for rendering React app
app.get('*', (req, res) => {
  const context = {};
  const appMarkup = ReactDOMServer.renderToString(
    <StaticRouter location={req.url} context={context}>
      <App />
    </StaticRouter>
  );

  if (context.url) {
    res.redirect(context.url);
  } else {
    res.status(200).send(`
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>SSR React App</title>
      </head>
      <body>
        <div id="root">${appMarkup}</div>
        <script src="/bundle.js"></script>
      </body>
      </html>
    `);
  }
});

此代码使用react-router-dom中的StaticRouter设置服务器端渲染,以根据请求的URL渲染适当的组件。


-2
投票

无论所有过程如何,您都需要经验丰富的网络专家的服务,这将能够帮助您摆脱困境但值得庆幸的是,您可以在专业人士的帮助下恢复和恢复。 bwh240pty@gmail

© www.soinside.com 2019 - 2024. All rights reserved.