[React] next.js CSR, SSR, SSG 簡單實作 implement

一、CSR

import { useEffect, useState } from 'react';

interface Post {
  userId: number,
  id: number,
  title: string,
  body: string,
}

const Home = () => {
  const [post, setPost] = useState<Post>();

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then((res) => res.json())
      .then((res) => setPost(res));
  }, []);

  return (
    <div>
      <h1>{post?.title}</h1>
      <p>{post?.body}</p>
    </div>
  )
}

export default Home



二、SSR

import type { GetServerSideProps } from 'next'

interface Post {
  userId: number,
  id: number,
  title: string,
  body: string,
}

interface HomeProps {
  post: Post,
}

const Home = ({ post }: HomeProps) => {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </div>
  )
}

export default Home

export const getServerSideProps: GetServerSideProps = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const post: Post = await res.json();

  return {
    props: {
      post,
    },
  }
};



三、SSG

import type { GetStaticProps } from 'next'

interface Post {
  userId: number,
  id: number,
  title: string,
  body: string,
}

interface HomeProps {
  post: Post,
}

const Home = ({ post }: HomeProps) => {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </div>
  )
}

export default Home

export const getStaticProps: GetStaticProps = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const post: Post = await res.json();

  return {
    props: {
      post,
    },
  }
};



留言

這個網誌中的熱門文章

[日文] Google日文輸入法 簡單安裝說明

[面試] 日月光 設備工程師

[Windows] 還我 win7 相片檢視器!!