【问题标题】:Adding Preloader in React Application在 React 应用程序中添加预加载器
【发布时间】:2021-03-19 15:32:25
【问题描述】:

我想在我的反应应用程序中添加一个预加载器。原因是,我的应用程序需要很多时间来加载。所以,我希望当我的所有应用程序内容完全准备好加载时,它会自动呈现。只要我的应用程序需要时间准备好加载,就会呈现预加载器。有可能吗?

我需要帮助。

这是我下面给出的应用代码:-

import React from 'react';
import Navbar from './Navbar'
import Home from './Home';
import About from './About';
import Services from './Services';
import Skills from './Skills';
import Contact from './Contact';
import Footer from './Footer';
import Reset from './Reset';

function App() {

  return (
    <>
      <Reset />
      <Navbar />
      <Home />
      <About />
      <Services />
      <Skills />
      <Contact />
      <Footer />
    </>
  );

}

export default App;

这是我的 Index.js 代码如下:-

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Preloader from './Preloader'

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    根据您想要实现的目标,您有很多选择。这就是使用像 React 这样的框架的目标。 我的建议是,将数据(API 调用等)的加载与 UI 的加载分开。使用异步方法加载可以执行的数据。我看到您正在使用功能组件,因此请查看反应挂钩并使用状态生成数据。 您有一种将默认值设置为状态的方法,因此所有内容都可以独立于数据生成进行渲染。稍后,当状态设置为您的数据时,网站将使用新数据自动呈现。

    特别是设置预加载用户界面,您可以查看此帖子: React - Display loading screen while DOM is rendering?

    【讨论】:

      【解决方案2】:

      我们通常会进行 API 调用,在数据准备好之前,我们会显示一个加载器。 SVG 加载器或任何其他加载器。

      您基本上需要设置三种状态来维护加载、错误和您的数据: 使用以下设置这将有助于您的项目。也可以访问我的github项目,从API and Loader获取Loader Code

      function App() {
        const [tours, setTours] = useState([]);
        const [error, setError] = useState(false);
        const [loading, setLoading] = useState(false);
      
        /*--- I am using fetch API here
        useEffect(() => {
          setLoading(true);
          fetch(url)
            .then((response) => {
              if (response.status >= 200 && response.status < 300) {
                return response.json();
              } else {
                throw new Error("Could not fetch data");
              }
            })
            .then((tours) => {
              setLoading(false);
              setTours(tours);
            })
            .catch((err) => console.log(err));
        }, []);
        ---*/
      
        const fetchTours = async () => {
          try {
            const response = await fetch(url);
            const tours = await response.json();
            setLoading(false);
            setTours(tours);
          } catch (error) {
            setLoading(false);
            setError(true);
          }
        };
        useState(() => {
          setLoading(true);
          fetchTours();
        }, []);
        // Functionality 1: Not Interested Button click
        const handleBtnClick = (id) => {
          const updatedTours = tours.filter((tour) => tour.id !== id);
          setTours(updatedTours);
        };
      
        // Functionality 2: Refresh Button click
      
        const handleRefresh = () => {
          setLoading(true);
          fetchTours();
        };
      
        // Let us do conditional rendering
        if (loading) {
          return (
            <div style={{ textAlign: "center", margin: "2rem 0" }}>
              <Loader />
            </div>
          );
        }
      
        if (error) {
          return <p>Error ...</p>;
        }
      
        return (
          <section>
            <p className="our-tours">
              {tours.length > 0 ? (
                "Our Tours"
              ) : (
                <div>
                  <p>No Tours Left</p>
                  <button className="btn" onClick={handleRefresh}>
                    Refresh
                  </button>
                </div>
              )}{" "}
            </p>
            <main className="App">
              {tours.length > 0 && (
                <Tours tours={tours} handleClick={handleBtnClick} />
              )}
            </main>
          </section>
        );
      }
      
      export default App;

      共有三种情况:

      1. 最初我们的加载是真实的,我们展示了我们的加载器。

      2. 当数据成功到达后,我们开始显示数据并隐藏我们的加载器。

      3. 当我们的 API 调用出现错误时,我们会显示错误消息。

      上述设置适用于所有情况:)

      【讨论】:

      • @Zidan Mehadi:希望答案有帮助。如果这样做,请单击勾选图标接受答案。谢谢:)
      猜你喜欢
      • 1970-01-01
      • 2018-05-16
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2020-08-21
      • 2017-05-08
      相关资源
      最近更新 更多