メインコンテンツにスキップ
バージョン: 6.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 コンポーネントはサーバーレンダリング中にアプリ全体を囲む必要があります。アプリには NavigationContainer が依然として必要であることに注意してください。ServerContainer はそれを置き換えるものではありません。

サーバーレンダリングガイド で、詳細なガイドと例を参照してください。

Ref

コンテナに ref をアタッチした場合、アプリのレンダリング後に現在の画面のオプションを取得できます。ref には getCurrentOptions というメソッドが含まれます。このメソッドは、ナビゲーションツリー内のフォーカスされた画面のオプションを含むオブジェクトを返します

const options = ref.current.getCurrentOptions();

その後、このオブジェクトから画面のオプションにアクセスし、HTML に配置できます

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

初期レンダリング時にナビゲータをレンダリングしていない場合、options オブジェクトは未定義になる可能性があります。

Props

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;
});