在React服务器端渲染中获取初始加载数据

时间:2016-05-02 11:28:53

标签: reactjs

在React服务器端渲染中从API获取初始加载数据的最佳做法是什么? 我曾尝试在构造函数方法中加载初始数据。但它不起作用。

1 个答案:

答案 0 :(得分: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');
    }

}