Conditional import or alternative in JavaScript (ReactJS WebApp)?

后端 未结 3 1202
猫巷女王i
猫巷女王i 2021-01-19 09:28

I\'m implementing internationalization for a ReactJS webapp. How can I avoid loading all language files?

import ru from \'./ru\';
import en from \'./en\';

         


        
3条回答
  •  太阳男子
    2021-01-19 10:26

    Looks like I am late here, but I would like to answer the approach I am using. I have an async component:

    import React from 'react';
    
    export default (loader, collection) => (
      class AsyncComponent extends React.Component {
        constructor(props) {
          super(props);
          this.Component = null;
          this.state = { Component: AsyncComponent.Component };
        }
    
        componentWillMount() {
          if (!this.state.Component) {
            loader().then((Component) => {
              AsyncComponent.Component = Component;
              this.setState({ Component });
    
            });
          }
        }
    
        render() {
          if (this.state.Component) {
            return (
              
            )
          }
    
          return null;
        }
      }
    );
    

    And we call it using:

    const page1 = asyncComponent(() => import('./page1')
      .then(module => module.default), { name: 'page1' });
    

    and then we use it with:

      
    

    This will ensure that loading is done dynamically.

提交回复
热议问题