点数
84点
感想
Next.jsの基礎がわかりやすく説明されていた。
最低限の使い方としては、本書の内容で十分だと思う。
基本
環境構築
- npx create-next-app next-portfolio --use-npm
- cd next-portfolio
- 不要ファイルを削除
 rm -rf pages/api/ pages/_document.js styles/Home.module.css
- pages/index.jsとstyles/globals.cssの中身を削除する。
 rm pages/index.js styles/globals.css
 touch pages/index.js styles/globals.css
- pages.index.jsを以下の内容にし、npm run devで確認
const Index = () => {
  return (
    <h1>Index</h1>
  );
};
export default Index;CSS
- 全体に適用するCSSはpages/_app.jsでimportする。
- node_modules配下のCSSファイルはimport文でインポートすることができる。import '@xxx/yyy.css'
 として<h1 className="h1-style">Hello</h1>
- https://nextjs.org/docs/basic-features/built-in-css-support
- node_modules配下以外のCSSファイルはインポートすることができない。
- CSS Modulesを使うと、コンポーネント毎にCSSファイルをインポートすることができる。
CSS Modules
.h1Text {
  color: red;
}import styles from '../styles/index.module.css'
const Index = () => {
  return (
    <h1 className={styles.h1Text}>Index</h1>
  );
};
export default Index;Linkコンポーネント
import Link from 'next/link'
import styles from '../styles/index.module.css'
const Index = () => {
  return (
    <>
      <h1 className={styles.h1Text}>Index</h1>
      <Link href="/contact">contact</Link>
    </>
  );
};
export default Index;<a href=”/contact”>contact</Link> でも動作はするが、画面が更新されるためスピードが遅くなる。
getStaticProps
- 静的にpropsやルートを定義するために、getStaticProps関数, getStaticPaths関数, getServerSideProps関数が用意されている。
- pagesディレクトリ内のコンポーネントにgetStaticProps関数を定義すると、ビルド時にデータを取得しコンポーネントのpropsとして扱えるようになる。
- getStaticProps関数とgetStaticPaths関数はSSGで、getServerSideProps関数はSSRで使うものなので、SPAでは使うことはないと思う。
- getStaticProps関数はビルド時に1回だけ実行される。
- getServerSideProps関数はリクエスト毎に実行される。
import Link from 'next/link'
const Contact = (props) => {
  return (
    <>
      <p>staticText: {props.staticText}</p>
      {props.posts.map(post => <p key={post.id}><Link href={`/detail/${post.id}`}>{post.title}</Link>: {(new Date(post.created_at)).toLocaleString()}</p>)}
    </>
  );
};
export default Contact;
export async function getStaticProps() {
  const res = await fetch('https://qiita.com/api/v2/items');
  const posts = await res.json();
  return {
    props: {
      staticText: 'テストデータ',
      posts: posts,
    }
  }
}ダイナミックルーティング
- pagesディレクトリ配下に[id].jsのようなファイルを作成すると、[]の中が動的なURLとなる。
 mkdir pages/detail;
 touch pages/detail/[id].js
- []内の値はuseRouterメソッドを使って取得することができる。
 ※ただし、そのままだとuseRouter().queryがundefinedになることがあるので、useEffect()内でisReadyメソッドで判定する必要があるとのこと。
 [参考サイト] https://craftime.net/posts/nextjs-get-query-parameters#useRouter
import { useRouter } from 'next/router';
import { useEffect,useState } from 'react';
import Link from 'next/link'
const SinglePost = () => {
  const [post, setPost] = useState({ title: '', body:'' });
  const router = useRouter();
  useEffect(() => {
    if (router.isReady) {
      fetch(`https://qiita.com/api/v2/items/${router.query.id}`)
        .then(res => res.json())
        .then(json => setPost(json));
    }
  }, [router]);
  return (
    <>
      <p>{post.title}</p>
      <pre>{post.body}</pre>
      <Link href="/contact">contact</Link>
    </>
  );
};
export default SinglePost; 
  
  
  
  

コメント