React - Display loading screen while DOM is rendering?

前端 未结 19 1587
我在风中等你
我在风中等你 2020-11-28 00:29

This is an example from Google Adsense application page. The loading screen displayed before the main page showed after.

I don\'t know how to do the same th

相关标签:
19条回答
  • 2020-11-28 01:10

    The most important question is: what do you mean by 'loading'? If you are talking about the physical element being mounted, some of the first answers here are great. However, if the first thing your app does is check for authentication, what you are really loading is data from the backend whether the user passed a cookie that labels them an authorized or unauthorized user.

    This is based around redux, but you can do easily change it to plain react state model.

    action creator:

    export const getTodos = () => {
      return async dispatch => {
        let res;
        try {
          res = await axios.get('/todos/get');
    
          dispatch({
            type: AUTH,
            auth: true
          });
          dispatch({
            type: GET_TODOS,
            todos: res.data.todos
          });
        } catch (e) {
        } finally {
          dispatch({
            type: LOADING,
            loading: false
          });
        }
      };
    };
    

    The finally part means whether the user is authed or not, the loading screen goes away after a response is received.

    Here's what a component that loads it could look like:

    class App extends Component {
      renderLayout() {
        const {
          loading,
          auth,
          username,
          error,
          handleSidebarClick,
          handleCloseModal
        } = this.props;
        if (loading) {
          return <Loading />;
        }
        return (
          ...
        );
      }
    
      ...
    
      componentDidMount() {
        this.props.getTodos();
      }
    
    ...
    
      render() {
        return this.renderLayout();
     }
    
    }
    

    If state.loading is truthy, we will always see a loading screen. On componentDidMount, we call our getTodos function, which is an action creator that turns state.loading falsy when we get a response (which can be an error). Our component updates, calls render again, and this time there is no loading screen because of the if statement.

    0 讨论(0)
提交回复
热议问题