“正在载入”的实现

Next.js 的 App 路由有一个约定:定义 loading.js,那么 Next.js 会自动在页面加载中显示这个组件,加载完成之后,自动隐藏该组件。

博客列表

// app/post/page.js

import Link from "next/link";

export default async function PostList() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const postList = await res.json();

  return (
    <>
      <ul>
        {postList.map((p) => (
          <li key={p.id}>
            <Link href={`/post/${p.id}`}>{p.title}</Link>
          </li>
        ))}
      </ul>
    </>
  );
}

博客详情

// app/loading.js
import React from "react";

export default function Loading() {
  return (
    <div style={{ color: "red", border: "1px solid #000", padding: "1rem" }}>
      正在载入……
    </div>
  );
}

import React from "react";

export default function PostDetailLoading() {
  return (
    <div style={{ color: "blue", border: "1px solid #000", padding: "1rem" }}>
      正在载入……
    </div>
  );
}

本章代码位于04/loading分支

要查看完整内容,请先登录