这是一个来自谷歌Adsense应用页面的例子。加载界面显示在主界面之前。

我不知道如何用React做同样的事情,因为如果我用React组件渲染加载屏幕,它不会在页面加载时显示,因为它必须等待DOM渲染之前。

更新:

我通过将屏幕加载器放在index.html中并在React componentDidMount()生命周期方法中删除它来举例说明我的方法。

示例和反应加载屏幕。


当前回答

最重要的问题是:“loading”是什么意思?如果你谈论的是被安装的物理元素,这里的一些第一个答案很好。然而,如果你的应用做的第一件事是检查身份验证,你真正加载的是来自后端的数据,用户是否传递了一个cookie,标签他们是授权或未授权的用户。

这是基于redux的,但你可以很容易地将其更改为普通的反应状态模型。

行动的创造者:

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
      });
    }
  };
};

最后一部分意味着无论用户是否被授权,在收到响应后加载屏幕都会消失。

下面是加载它的组件的样子:

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();
 }

}

如果状态。加载是真实的,我们总是会看到加载屏幕。在componentDidMount上,我们调用getTodos函数,它是一个转换状态的动作创建器。当我们得到一个响应(这可能是一个错误)加载假。我们的组件更新,再次调用渲染,这一次没有加载屏幕,因为if语句。

其他回答

这将发生在ReactDOM.render()控制根目录<div>之前。也就是说,你的应用程序到那时还没有被安装。

所以你可以把你的加载器添加到index.html文件的根目录<div>。在React接管之前,这将在屏幕上可见。

您可以使用任何最适合您的加载器元素(例如带有动画的svg)。

您不需要在任何生命周期方法上删除它。React会用你渲染的<App/>替换它的根<div>的所有子元素,就像我们在下面的动图中看到的那样。

关于CodeSandbox的例子

index . html

<head>
  <style>
    .svgLoader {
      animation: spin 0.5s linear infinite;
      margin: auto;
    }
    .divLoader {
      width: 100vw;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  </style>
</head>

<body>
  <div id="root">
    <div class="divLoader">
      <svg class="svgLoader" viewBox="0 0 1024 1024" width="10em" height="10em">
        <path fill="lightblue"
          d="PATH FOR THE LOADER ICON"
        />
      </svg>
    </div>
  </div>
</body>

index.js

在ReactDOM.render()运行之前,使用调试器检查页面。

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

debugger; // TO INSPECT THE PAGE BEFORE 1ST RENDER

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

只要在<div id="root"></div>标签内添加内容,你就应该很好了!

// Example:

<div id="root">
   <div id="pre-loader">
        <p>Loading Website...</p>
        <img src="/images/my-loader.gif" />
   </div>
</div>

一旦<App />被加载,React会自动忽略<div id="root">标签内的所有内容,用你实际的应用程序覆盖它!

我使用的是react-progress-2 npm包,它是零依赖的,在ReactJS中工作得很好。

https://github.com/milworm/react-progress-2

安装:

NPM安装react-progress-2

在项目中包含react-progress-2/main.css。

导入“node_modules / react-progress-2 / main.css”;

包括react-progress-2,并把它放在顶部组件的某个地方,例如:

import React from "react";
import Progress from "react-progress-2";

var Layout = React.createClass({
render: function() {
    return (
        <div className="layout">
            <Progress.Component/>
                {/* other components go here*/}
            </div>
        );
    }
});

现在,无论何时你需要显示一个指示器,只需调用Progress.show(),例如:

loadFeed: function() {
    Progress.show();
    // do your ajax thing.
},

onLoadFeedCallback: function() {
    Progress.hide();
    // render feed.
}

请注意,show和hide调用是堆叠的,因此在n个连续的show调用之后,您需要执行n个hide调用来隐藏一个指示器,或者您可以使用Progress.hideAll()。

如果你使用react-router来管理你的应用程序的路由,你可以很容易地添加加载屏幕与我做的react-router加载库。

它也会影响页面切换,但我认为,如果你想预装第一页,自然也会预装其他页面。

这个方法和悬疑方法的区别在于,有了这个库,你可以在获取数据的同时继续加载。 基本上,这个方法非常类似于在组件中使用isLoading状态,但是如果您有很多不同的页面,则更容易实现。

使用

在路由器部分,从react-router-loading导入Switch和Route,而不是从react-router-dom导入

import { Switch, Route } from "react-router-loading";

<Switch>
    <Route path="/page1" component={Page1} />
    <Route path="/page2" component={Page2} />
    ...
</Switch>

在切换前必须加载的每条路线上添加加载道具

<Switch>
    // data will be loaded before switching
    <Route path="/page1" component={Page1} loading />

    // instant switch as before
    <Route path="/page2" component={Page2} />
    ...
</Switch>

在加载道具路由中提到的组件的初始加载方法的末尾添加loadingContext.done()(在这种情况下是Page1)

import { LoadingContext } from "react-router-loading";
const loadingContext = useContext(LoadingContext);

const loading = async () => {
    // loading some data

    // call method to indicate that loading is done and we are ready to switch
    loadingContext.done();
};

你可以指定加载屏幕,将显示在你的应用程序的第一次加载

const MyLoadingScreen = () => <div>Loading...</div>

<Switch loadingScreen={MyLoadingScreen}>
...
</Switch>

解决这个问题的方法是在你的渲染函数中这样做:

constructor() {
    this.state = { isLoading: true }
}

componentDidMount() {
    this.setState({isLoading: false})
}

render() {
    return(
        this.state.isLoading ? *showLoadingScreen* : *yourPage()*
    )
}

在构造函数中将isLoading初始化为true,在componentDidMount上将其初始化为false。