一、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,
},
}
};
留言
張貼留言