Sfoglia il codice sorgente

動的ページ作成

main
shigeo.shinohara 2 anni fa
parent
commit
dfa25b8e5a
3 ha cambiato i file con 83 aggiunte e 2 eliminazioni
  1. +13
    -0
      lib/strapi.ts
  2. +5
    -2
      next.config.js
  3. +65
    -0
      pages/guitar/[id].tsx

+ 13
- 0
lib/strapi.ts Vedi File

@@ -12,3 +12,16 @@ export const fetchGuitars = async (): Promise<Guitar[]> => {
const guitars: Guitar[] = await response.json().then((json) => json.data);
return guitars;
};

/**
* Guitar情報取得処理
*/
export const fetchGuitarDetail = async (id: string): Promise<Guitar> => {
// StrapiのAPIを呼び出し
const response = await fetch(
`${process.env.NEXT_PUBLIC_STRAPI_URL}/api/guitars/${id}?populate=*`
);
// apiのresponseからdata部のみ取り出し
const guitar: Guitar = await response.json().then((json) => json.data);
return guitar;
};

+ 5
- 2
next.config.js Vedi File

@@ -1,6 +1,9 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
images: {
domains: ["res.cloudinary.com"],
},
};

module.exports = nextConfig
module.exports = nextConfig;

+ 65
- 0
pages/guitar/[id].tsx Vedi File

@@ -0,0 +1,65 @@
import React, { FC } from "react";
import { GetStaticPaths, GetStaticProps, GetStaticPropsContext } from "next";
import { fetchGuitarDetail, fetchGuitars } from "../../lib/strapi";
import { ParsedUrlQuery } from "querystring";
import { Guitar } from "../../type/guitars";
import Image from "next/image";

const Detail: FC<Props> = ({ guitar }) => {
return (
<div>
<div>ID: {guitar?.id}</div>
<div>名前:{guitar?.attributes.name}</div>
<div>説明:{guitar?.attributes.description}</div>
<div>
<Image
src={guitar?.attributes.image.data[0].attributes.url}
height={240}
width={560}
/>
</div>
</div>
);
};

interface Props {
guitar: Guitar;
}

interface IParams extends ParsedUrlQuery {
id: string;
}

// ===============================
// 静的サイト作成時にはgetStaticPropsの中で
// 表示データを作成する
// ===============================
export const getStaticProps: GetStaticProps = async (ctx) => {
const { id } = ctx.params as IParams;
const guitar = await fetchGuitarDetail(id);
return {
props: {
guitar,
},
};
};

// ================================
// 表示可能なデータを取得する
// ================================
export const getStaticPaths: GetStaticPaths = async () => {
const guitars = await fetchGuitars();
// とりうるIDの一覧を取得する
const paths = guitars.map((guitars) => ({
params: {
id: guitars.id.toString(),
},
}));

return {
paths,
fallback: true,
};
};

export default Detail;

Loading…
Annulla
Salva