2016-05-02 12 views
2

リア・サーバ側レンダリングでAPIから初期ローディング・データをフェッチするためのベスト・プラクティスは何ですか? コンストラクタメソッドで初期データを読み込もうとしました。しかし、それは動作していません。リア・サーバ側レンダリングでの初期ローディング・データの取得

+1

からのスニペットは素晴らしいことだです。コード?問題?試み?これらの質問がない質問は、通常はあまりにも広すぎるとして閉じられているか、まったく回答がありません。 –

+0

[非同期に初期化されたReact.jsコンポーネントのサーバーサイドレンダリングのための戦略](http://stackoverflow.com/questions/25983001/strategies-for-server-side-rendering-of-asynchronously-initialized-react- js-comp) – iofjuupasli

+1

外部APIからデータを取り出し、そのデータを使ってコンポーネントをレンダリングする必要があります。どのように私はそれについて行く必要があります。私はその目的のためにコンストラクタメソッドで外部APIをヒットする必要があります。 –

答えて

-5

componentDidMount()を使用して、データをフェッチするアクションを開始します。それはあなたの店を埋めるでしょう。 isomorphic/universal reactを利用することで、ストアのJSONをマークアップに埋め込み、クライアント側に読み込むことができます。

+1

'componentDidMount'がサーバサイドのレンダリングの場合に機能しないため、Downvotedです。リファレンス:https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount –

+0

十分な場合は、コンストラクタまたはcomponentWillMount()を使用して、 –

0

redux-sagaを使用して、サーバー側で初期データを取得するのを手伝ってください。以下は

は、あなたの質問にいくつかの追加情報を追加した場合、私のReact example that uses Redux Saga and Hapi for Server-side Rendering

class ReactController { 

    _html = null; 

    mapRoutes(server) { 
     server.route({ 
      method: 'GET', 
      path: '/{route*}', 
      handler: async (request, reply) => { 
       const store = ProviderService.createProviderStore({}, true); 
       const context = {}; 
       const app = (
        <RouterWrapper 
         store={store} 
         location={request.path} 
         context={context} 
         isServerSide={true} 
        /> 
       ); 

       this._html = (this._html === null) ? await this._loadHtmlFile() : this._html; 

       store.runSaga(rootSaga).done.then(async() => { 
        const renderedHtml = renderToString(app); 
        const state = store.getState(); 
        const initialState = { 
         ...state, 
         renderReducer: { 
          isServerSide: true, 
         }, 
        }; 

        const html = this._html 
         .slice(0) 
         .replace('{title}', state.metaReducer.title) 
         .replace('{description}', state.metaReducer.description) 
         .replace('{content}', renderedHtml) 
         .replace('{state}', JSON.stringify(initialState)); 

        if (context.url) { 
         console.info('context', context); 
        } 

        reply(html); 
       }); 

       renderToString(app); 

       store.endSaga(); 
      }, 
     }); 
    } 

    async _loadHtmlFile() { 
     const htmlPath = path.resolve(__dirname, '../../public/index.html'); 

     return fse.readFile(htmlPath, 'utf8'); 
    } 

} 
関連する問題