“正在载入”的实现

193
2023/06/17 13:53:22

同时,loading.js 也是层级性的:本路由里没有的话,往父路由里找,一直到 app/loading.js。如果最终没有任何地方有这个文件,那么就不启用这个功能。

我们将通过一个从 https://jsonplaceholder.typicode.com 获取博客的案例进行演示。

博客列表

// 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/post/[id]/page.js

import React from "react";

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

根目录下创建loading.js

博客详情下创建loading.js

import React from "react";

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

本章代码位于04/loading分支