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

前端 未结 6 1089
一向
一向 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条回答
  •  萌比男神i
    2020-12-12 10:15

    Wanna share with you my approach of server side rendering using Flux, little be simplified for example:

    1. Let's say we have component with initial data from store:

      class MyComponent extends Component {
        constructor(props) {
          super(props);
          this.state = {
            data: myStore.getData()
          };
        }
      }
      
    2. If class require some preloaded data for initial state let's create Loader for MyComponent:

       class MyComponentLoader {
          constructor() {
              myStore.addChangeListener(this.onFetch);
          }
          load() {
              return new Promise((resolve, reject) => {
                  this.resolve = resolve;
                  myActions.getInitialData(); 
              });
          }
          onFetch = () => this.resolve(data);
      }
      
    3. Store:

      class MyStore extends StoreBase {
          constructor() {
              switch(action => {
                  case 'GET_INITIAL_DATA':
                  this.yourFetchFunction()
                      .then(response => {
                          this.data = response;
                          this.emitChange();
                       });
                   break;
          }
          getData = () => this.data;
      }
      
    4. Now just load data in router:

      on('/my-route', async () => {
          await new MyComponentLoader().load();
          return ;
      });
      

提交回复
热议问题