Strategies for server-side rendering of asynchronously initialized React.js components

前端 未结 6 1090
一向
一向 2020-12-12 09:51

One of the biggest advantages of React.js is supposed to be server-side rendering. The problem is that the key function React.renderC

6条回答
  •  再見小時候
    2020-12-12 10:22

    I know this question was asked a year ago but we had the same problem and we solve it with nested promises that were derived from the components that are going to be render. In the end we had the all data for the app and just sent it down the way.

    For example:

    var App = React.createClass({
    
        /**
         *
         */
        statics: {
            /**
             *
             * @returns {*}
             */
            getData: function (t, user) {
    
                return Q.all([
    
                    Feed.getData(t),
    
                    Header.getData(user),
    
                    Footer.getData()
    
                ]).spread(
                    /**
                     *
                     * @param feedData
                     * @param headerData
                     * @param footerData
                     */
                    function (feedData, headerData, footerData) {
    
                        return {
                            header: headerData,
                            feed: feedData,
                            footer: footerData
                        }
    
                    });
    
            }
        },
    
        /**
         *
         * @returns {XML}
         */
        render: function () {
    
            return (
                
    ); } });

    and in the router

    var AppFactory = React.createFactory(App);
    
    App.getData(t, user).then(
        /**
         *
         * @param data
         */
        function (data) {
    
            var app = React.renderToString(
                AppFactory(data)
            );       
    
            res.render(
                'layout',
                {
                    body: app,
                    someData: JSON.stringify(data)                
                }
            );
    
        }
    ).fail(
        /**
         *
         * @param error
         */
        function (error) {
            next(error);
        }
    );
    

提交回复
热议问题