Show loading icon before first react app initialization

﹥>﹥吖頭↗ 提交于 2019-12-11 05:38:57

问题


What is the standard way of showing a loader icon before browser downloads all js files and loads react application.

Can I do something like this without breaking anything?

<div id="content" class="app">
  Loading...
</div>

回答1:


Yes.

Once your javascript has loaded, you can replace Loading... by rendering your react app into the same <div>

render(
  <App />, 
  document.getElementById('content')
);



回答2:


One way of doing this using component life cycle methods.

class App extends React.Component {
    constructor(props){
      super(props);
      this.state = {
        loading: true
      };
    }
  
    componentWillMount(){
       this.setState({loading: true}); //optional 
    }

    componentDidMount(){
        this.setState({loading: false}) 
    }
  
    render() {
        return (
            <section className="content">
              {this.state.loading && 'loading...'} {/*You can also use custom loader icon*/}
              <p>Your content comes here</p>
              {this.props.children}
            </section>
        );
    }
}

ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
  
</div>


来源:https://stackoverflow.com/questions/41679912/show-loading-icon-before-first-react-app-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!