尝试SSR,但得到“ ServerStyleSheets不是构造函数”

我按照网站上的Material-UI指南配置了SSR,这是我的服务器端代码:

//server.js
...
...
...
const app = express();

app.use('/dist',express.static('dist'));

app.use((req,res) => {

  const sheets = new ServerStyleSheets();

  const html = renderToString(
    sheets.collect(
      <DataProvider>
        <StaticRouter location={req.url}>
          <MuiThemeProvider theme={theme}>
            <App />
          </MuiThemeProvider>
        </StaticRouter>
      </DataProvider>
    )
  );

  const css = sheets.toString();

  res.send(`
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
        <meta name="viewport" content="minimum-scale=1,initial-scale=1,width=device-width,shrink-to-fit=no" />
        <meta name="theme-color" content="#000000" />
        <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

        <title>My React App</title>
        <style id="jss-server-side">${css}</style>
      </head>
      <body>
        <div id="root">${html}</div>
        <script src='main.js' async></script>
      </body>
    </html>
  `);
});

这是我的客户端脚本:

//client.js
...
...
...
function Main() {
  React.useEffect(() => {
    const jssStyles = document.getElementById('jss-server-side');
    if (jssStyles) {
      jssStyles.parentNode.removeChild(jssStyles);
    }
  },[]);

  return (
    <I18nextProvider i18n={i18n}>
      <DataProvider>
        <BrowserRouter>
          <MuiThemeProvider theme={theme}>
            <App />
          </MuiThemeProvider>
        </BrowserRouter>
      </DataProvider>
    </I18nextProvider>
  );
}

hydrate(<Main />,document.getElementById('root'));

它可以构建,但是在访问本地主机时出现此错误:

TypeError: l.ServerStyleSheets is not a constructor
    at project-path/dist/main.js:1:301839
    at Layer.handle [as handle_request] (project-path/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (project-path/node_modules/express/lib/router/index.js:317:13)
    at project-path/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (project-path/node_modules/express/lib/router/index.js:335:12)
    at next (/project-path/node_modules/express/lib/router/index.js:275:10)
    at expressInit (project-path/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (project-path/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (project-path/node_modules/express/lib/router/index.js:317:13)
    at project-path/node_modules/express/lib/router/index.js:284:7

我正在使用

“ @ material-ui / core”:“ ^ 4.1.2”, “表达”:“ ^ 4.17.1”, “ react”:“ ^ 16.8.6”, “ webpack”:“ ^ 4.41.2”,

请帮助我解决此问题,我正在尝试将SSR添加到已完成的SPA中...

xfkeshe3 回答:尝试SSR,但得到“ ServerStyleSheets不是构造函数”

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3041594.html

大家都在问