跳到主要内容
版本:7.x

ServerContainer

ServerContainer 组件提供了在服务器上使用正确的导航状态渲染你的应用的工具。

示例

// 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 不会取代它。

请参阅服务端渲染指南以获取详细指南和示例。

Ref

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

const options = ref.current.getCurrentOptions();

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

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

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

Props

location

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

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

通常,你将基于传入的请求构造此对象。

使用 Koa 的基本示例(请勿在生产环境中使用)

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

ctx.body = html;
});