Skip to main content
Version: 6.x

ServerContainer

ServerContainer 组件提供了实用程序,可以使用正确的 导航状态 在服务器上呈现你的应用。

¥The ServerContainer component provides utilities to render your app on server with the correct navigation state.

示例:

¥Example:

// Ref which will be populated with the screen options
const ref = React.createRef();

// Location object containing the `pathname` and `search` fields of the current URL
const location = { pathname: '/profile', search: '?user=jane' };

// Get rendered HTML
const html = ReactDOMServer.renderToString(
<ServerContainer ref={ref} location={location}>
<App />
</ServerContainer>
);

// Then you can access the options for the current screen in the ref
const options = ref.current.getCurrentOptions(); // { title: 'My Profile' }

ServerContainer 组件应在服务器渲染期间封装你的整个应用。请注意,你的应用中仍然需要 NavigationContainerServerContainer 不会取代它。

¥The ServerContainer component should wrap your entire app during server rendering. Note that you still need a NavigationContainer in your app, ServerContainer doesn't replace it.'

请参阅 server rendering guide 了解详细指南和示例。

¥See the server rendering guide for a detailed guide and examples.

参考号

¥Ref

如果将 ref 附加到容器,则可以在渲染应用后获取当前屏幕的选项。ref 将包含一个名为 getCurrentOptions 的方法,该方法将返回一个对象,其中包含导航树中聚焦屏幕的选项:

¥If you attach a ref to the container, you can get the options for the current screen after rendering the app. The ref will contain a method called getCurrentOptions which will return an object with options for the focused screen in the navigation tree:

const options = ref.current.getCurrentOptions();

然后你可以从此对象访问屏幕选项并将其放入 HTML 中:

¥Then you can access the options for the screen from this object and put it in the HTML:

<title>{options.title}</title>
<meta name="description" content={options.description} />

请注意,如果你不在初始渲染中渲染导航器,则 options 对象可能未定义。

¥Note that the options object can be undefined if you are not rendering a navigator on the initial render.

属性

¥Props

location

Location 对象,包含用于服务器渲染输出的位置。你可以在浏览器中传递与 location 对象匹配的 pathnamesearch 属性:

¥Location object containing the location to use for server rendered output. You can pass the pathname and search properties matching the location object in the browsers:

<ServerContainer location={{ pathname: '/profile', search: '' }}>
<App />
</ServerContainer>

通常,你将根据传入请求构造此对象。

¥Normally, you'd construct this object based on the incoming request.

Koa 的基本示例(不要在生产中按原样使用):

¥Basic example with Koa (don't use as is in production):

app.use(async (ctx) => {
const html = ReactDOMServer.renderToString(
<ServerContainer location={{ pathname: ctx.path, search: ctx.search }}>
<App />
</ServerContainer>
);

ctx.body = html;
});