【问题标题】:Let only one page be server-side rendered with Meteor让 Meteor 只在服务器端渲染一个页面
【发布时间】:2022-01-18 00:04:05
【问题描述】:

我的 Meteor/React 应用程序应该呈现一个静态页面,除了具有响应式 UI 的响应式页面。静态包在浏览器中显示后甚至不需要使用 React 魔法“水合”。尽管使用 React 组件,服务器上的服务器端渲染将是动态的。

我得到了它的工作,但我不确定这是否是预期的官方方式。

文件 import/client/routes.js

...
<Route path="/reactive/pages/:id" component={ReactiveComponent} />
<Route path="/static_url" />
...

文件 server/main.jsx

...
onPageLoad((sink) => {
  if (sink.request.path === '/static_url) {
    sink.renderIntoElementById('app', renderToString(
      <StaticPage />,
    ));
  }
});
...

文件 client/main.js

...
import { Routes } from '../imports/client/routes';

Meteor.startup(() => {
  ...

  if (window.location.pathname !== '/offer_pdf') {
    render(Routes, document.getElementById('app'));
  }
});
...

尤其是在渲染依赖于 URI 时,对我来说似乎有点 hacky。是否存在更优雅的解决方案?

【问题讨论】:

  • 我也这样做。它有效,但我不确定这是最好的方法。

标签: reactjs meteor server-side-rendering


【解决方案1】:

我不认为有什么官方的,但总的来说,当然,使用路由器来渲染不同的页面是一个好主意,所以我认为值得指出的是你可以在服务器上使用 react-router还有:

import React from "react";
import { renderToString } from "react-dom/server";
import { onPageLoad } from "meteor/server-render";
import { StaticRouter } from 'react-router-dom';

import App from '/imports/ui/app.jsx';

onPageLoad(sink => {
  const context = {};
  sink.renderIntoElementById("app", renderToString(
    <StaticRouter location={sink.request.url} context={context}>
      <App />
    </StaticRouter>
  ));

  /* Context is written by the routes in the app. The NotFound route, used
    when, uhm, no route is found, sets the status code. Here we set it on the
    HTTP response to get a hard 404, not just a soft 404. Important for Google bot.
  */
  context.statusCode && sink.setStatusCode(context.statusCode);

  // add title to head of document if set by route
  sink.appendToHead(`<title>${context.title || 'My page'}</title>`);
});

App 中,您可以使用通常的SwitchRoute 标签来指定不同的路由。例如,您可以只指定要在服务器上渲染的路由。

【讨论】:

  • 不幸的是,react-router-domreact-router 都没有包含 StaticRouter,尽管在文档中提到了它:https://v5.reactrouter.com/web/api/StaticRouter(我使用了 6.2.1 版,但他们没有更改文档 vor v6)
  • 必须像import StaticRouter from 'react-router-dom/server';这样导入(文档中甚至是错误的)。但后来我得到Error running template: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object
  • 对不起,一定是import { StaticRouter } from 'react-router-dom/server';
猜你喜欢
  • 2023-01-19
  • 2018-01-16
  • 2019-06-03
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 2013-02-11
相关资源
最近更新 更多