在資料尚未載入或回傳時,畫面會呈現空白或停止狀態,這樣會造成不好的使用者體驗,所以通常都會加一個 Loading 畫面,告知使用者目前應用程式有在運作,讓使用者願意等待而不是離開頁面
以下介紹兩種常見又簡單的 Loading:
可以依據要顯示的元件架構製作預覽框架,讓使用者有心理準備(?)接下來會出現的畫面

安裝套件
yarn add react-loading-skeleton
在 App.js 中引入 CSS 樣式
import "react-loading-skeleton/dist/skeleton.css";
在 Home.js 中宣告一個狀態變數 loading ,初始值為 true ,執行完 getAllPost 後值設定為 false

然後將 loading 傳給 <Post />
<Post data={posts} loading={loading} />
在 components/Post.js 中引入 Skeleton ,然後依照官方文件的說明,搭配 loading 進行條件渲染
(<Skeleton /> 直接跟內容放在一起,樣式也可以依照需求微調)
import Skeleton from 'react-loading-skeleton';
<span className="ml-3 opacity-80 text-sm">
    {loading ? <Skeleton width="25%" /> : formatDate(el.createdAt)}
</span>

完成後就會呈現這樣~非常乾淨俐落呢!

PostDetail.js 也是相同概念~

接下來介紹另一種,非常適合放動畫用的工具 - Lottie,主要的兩大用法:
(今天使用較方便的第二個用法!)
尋找想要使用的素材

找到後點擊「Download」→ 「Lottie JSON」,下載 json 檔(要先登入!)

安裝套件
yarn add lottie-web
然後把動畫的 json 檔放進專案中 → src/animations/

接著建立 components/Loading.js ,依照官方文件使用 lottie.loadAnimation() ,並設定需要的資料
(return () => instance.destroy(); 是為了避免 useEffect 渲染兩次而出現兩個重複的 Loading 動畫)
import React, { useEffect, useRef } from 'react';
import lottie from 'lottie-web';
import loadingAnimation from '../animations/98742-loading.json';
export default function Loading() {
    const animation = useRef(null);
    useEffect(() => {
        const instance = lottie.loadAnimation({
            container: animation.current,
            renderer: 'svg',
            loop: true,
            autoplay: true,
            animationData: loadingAnimation,
        });
        return () => instance.destroy();
    }, []);
    return (
        <div className="absolute w-full h-full flex items-center justify-center">
            <div className="" ref={animation}></div>
        </div>
    );
}
最後把 <Loading /> 加進 PostDetail.js

這樣就能顯示 Loading 動畫啦~
