当我在 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`.
我错过了什么?
您的代码片段似乎正在尝试使用 React Router 对 React 应用程序进行服务器端渲染(SSR)。但是,这种方法存在一些问题:
// 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渲染适当的组件。