📜  如何在反应路由器的路由之间显示一个简单的加载指示器?

📅  最后修改于: 2022-05-13 01:56:38.728000             🧑  作者: Mango

如何在反应路由器的路由之间显示一个简单的加载指示器?

在准备要显示的页面时显示加载屏幕是一种很好的做法。在 react-router 中的路由之间显示一个简单的加载指示器非常容易。

创建反应应用程序:

  • 第 1 步:使用以下命令创建一个 React 应用程序:

    npx create-react-app foldername
  • 第 2 步:创建项目文件夹(即文件夹名称)后使用以下命令移动到该文件夹:

    cd foldername

项目结构:它将如下所示。

如上图所示创建Home.jsApp.js。

实现:现在在App.js文件中写下以下代码。在这里,App 是我们编写代码的默认组件。

App.js
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import {useState} from "react";
import Home from'./components/Home';
  
function App() {
  return (
    // Create route for each page, since we 
    // have only one page. So we are defining 
    // only one route.
    
      
    
  );
}
  
export default App;


Home.js
import React from "react";
import {useEffect, useState} from "react";
  
const Home = () => {
  
    // Set loading state to true initially
    const [loading, setLoading] = useState(true);
      
    useEffect(() => {
      // Loading function to load data or 
      // fake it using setTimeout;
      const loadData = async () => {
  
        // Wait for two second
        await new Promise((r) => setTimeout(r, 2000));
  
        // Toggle loading state
        setLoading((loading) => !loading);
      };
        
      loadData();
    }, [])
      
    // If page is in loading state, display 
    // loading message. Modify it as per your 
    // requirement.
    if (loading) {
        return 
Loading....
    }            // If page is not in loading state, display page.     else {         return

Home

    } }    export default Home;


主页.js

import React from "react";
import {useEffect, useState} from "react";
  
const Home = () => {
  
    // Set loading state to true initially
    const [loading, setLoading] = useState(true);
      
    useEffect(() => {
      // Loading function to load data or 
      // fake it using setTimeout;
      const loadData = async () => {
  
        // Wait for two second
        await new Promise((r) => setTimeout(r, 2000));
  
        // Toggle loading state
        setLoading((loading) => !loading);
      };
        
      loadData();
    }, [])
      
    // If page is in loading state, display 
    // loading message. Modify it as per your 
    // requirement.
    if (loading) {
        return 
Loading....
    }            // If page is not in loading state, display page.     else {         return

Home

    } }    export default Home;

运行应用程序的步骤:从项目的根目录使用以下命令运行应用程序:

npm start

输出:现在打开浏览器并转到http://localhost:3000/ ,您将看到以下输出:

结果