ReferenceError:文档未定义(反应路由)

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

当我在 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
1个回答
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渲染适当的组件。

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