【问题标题】:Fetching initial loading data in React server side rendering在 React 服务器端渲染中获取初始加载数据
【发布时间】:2016-08-27 03:41:58
【问题描述】:

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

【问题讨论】:

  • 如果您在问题中添加一些其他信息会很棒。代码?问题?尝试?没有这些的问题通常会因为过于宽泛或根本没有得到任何答案而被关闭。
  • 我需要从外部 API 获取数据并使用该数据来呈现组件。我该怎么做。为此,我是否应该在构造函数方法中使用外部 api。

标签: reactjs


【解决方案1】:

看看使用 redux-saga 来帮助你在服务器端获取初始数据。

下面是我React example that uses Redux Saga and Hapi for Server-side Rendering的sn-p

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

}

【讨论】:

    猜你喜欢
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2020-04-02
    • 2015-10-16
    • 1970-01-01
    • 2015-05-07
    相关资源
    最近更新 更多