背景:这个dome是方便让我们了解next中是需要这么通过接口请求获取动态数据的,动态获取静态页面的数据,例如首页,动态获取动态页面的数据,例如商品详情页等,让我们在项目中能够更加的得心应手,
组件
layout组件
export default function Layout({ children }) {
return (
<div>
{children}
</div>
)
}
movie组件
import styles from '../styles/Movie.module.css'
import axios from 'axios'
import { baseURL } from '../axiosConfig'
export default function Movie({ data, title }) {
return (
<div className={styles.main}>
<div>{title}</div>
<div className={styles.content}>
{data.map((v) => {
return (
<div key={v.vid}>
<img src={v.url} />
<p>介绍</p>
</div>
)
})}
</div>
</div>
)
}
export function loadMovie() {
return axios.get('/api/movie', { baseURL })
}
swiper组件
import { Carousel } from 'react-responsive-carousel'
import 'react-responsive-carousel/lib/styles/carousel.min.css'
import axios from 'axios'
import { baseURL } from '../axiosConfig'
import Link from 'next/link'
export default function Swiper({ data }) {
return (
<>
<Carousel showStatus={false} showIndicators={false}>
{data.map((v) => {
return (
<div key={v.vid}>
<img src={v.url} />
<button>
<Link
href="/detail/[id]"
as={`/detail/${v.vid}`}
>
点击跳转详情页
</Link>
</button>
</div>
)
})}
</Carousel>
</>
)
}
export function loadSwiper() {
return axios.get('/api/swiper', {
baseURL,
})
}
静态页面请求(getStaticProps)
import Swiper, { loadSwiper } from '../components/Swiper'
import Movie, { loadMovie } from '../components/Movie'
import Layout from '../components/Layout'
export default function Home({ swiper, movie }) {
return (
<>
<Layout>
<Swiper data={swiper} />
<Movie data={movie} title="电影" />
</Layout>
</>
)
}
export async function getStaticProps() {
let { data: swiper } = await loadSwiper()
let { data: movie } = await loadMovie()
return {
props: {
swiper,
movie,
},
}
}
动态页面请求(getStaticPaths和getStaticProps),对应的页面创建名称 [id].js
import Layout from '../../components/Layout'
import axios from 'axios'
import { baseURL } from '../../axiosConfig'
export default function Detail({ detail }) {
return (
<Layout>
<h2>{detail.author}</h2>
<h3>{detail.publish}</h3>
<h4>{detail.sub}</h4>
<h1>{detail.title}</h1>
<div dangerouslySetInnerHTML={{ __html: detail.content }}></div>
</Layout>
)
}
export async function getStaticPaths() {
let { data } = await axios.get('/api/videos', { baseURL })
let paths = data.map((id) => ({ params: { id } }))
return {
paths,
fallback: false,
}
}
export async function getStaticProps({ params }) {
let id = params.id
let { data: detail } = await axios.get(`/api/detail?id=${id}`, {
baseURL,
})
return {
props: {
detail,
},
}
}