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
元件應該在伺服器呈現期間包裝整個應用程式。請注意,您的應用程式中還是需要一個 NavigationContainer
,ServerContainer
沒有替代它。'
請參閱伺服器呈現指南
,以取得詳細的指南和範例。
參照
如果您將ref
附加至容器,您可以在呈現應用程式之後取得當前景象的選項。ref
包含一個名為getCurrentOptions
的方法,這個方法會傳回一個物件,其中包含導覽樹中焦點畫面的選項
const options = ref.current.getCurrentOptions();
然後,您可以從這個物件存取畫面的選項,並將它放入 HTML 中
<title>{options.title}</title>
<meta name="description" content={options.description} />
請注意,如果您在初始的呈現中沒有呈現導覽器,options
物件則可能為 undefined。
道具
location
包含要使用的伺服器呈現輸出的位置的位置物件。您可以傳入與瀏覽器中的location
物件匹配的 pathname
和 search
屬性
<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;
});