![](/img/trans.png)
[英]import a single getServerSideProps method to multiple pages in Nextjs
[英]Nextjs - Fetching single post data using getServerSideProps
我正在使用 Nextjs + Strapi 构建一个新闻网站,因为新闻网站是高度动态的并且需要按分钟推送更新,我不能使用getStaticProps
因为即使使用增量 static 再生这种方法在构建中获取数据也没有任何意义,在此外,该网站必须具有高级搜索和用户帐户,他们可以在其中个性化他们想要阅读的新闻类别。
我能够使用getServerProps
在布局中获取主菜单数据(新闻类别),我创建了动态路由,但是当涉及到属于它的新闻文章获取(单一类别)时,我找不到任何明确的文档。
我尝试在./pages/api
文件夹getCategoryData.js
中创建一个外部方法,以使用axios
和category.slug
作为变量从外部 api(Strapi 后端)获取单个类别数据,我能够正确获取数据但我尝试了很多将类别数据分配给页面正文方法内的const category
的方法,它不成功并返回未定义。
这正是我在单一类别页面中所做的:./pages/category/ ./pages/category/[slug]/index.js
import { useRouter } from 'next/router'
import DefaultLayout from "../../../components/layouts/default";
import { getCategory } from "../../api/getCategoryData";
const CategoryArticles = ({ menuItems }) => {
const router = useRouter()
const { slug } = router.query
const category = getCategoryData(slug);
console.log(category) // here returns undefined !!!
return (
<DefaultLayout menuItems={ menuItems }>
<div> { category.name } </div>
</DefaultLayout>
);
}
export default CategoryArticles
// Note: I tried to call getCategoryData(slug) here but could not export the slug variable outside of
// page body method, also tried to use getInitialProps method for that, it did not work since I am
// using getServerSideProps.
export async function getServerSideProps() {
const res = await fetch('http://localhost:1337/categories')
const data = await res.json()
return {
props: { menuItems: data },
}
}
./pages/api/getCategoryData.js
中的一个
import axios from "axios";
export const getCategoryData = async (slug) => {
const response = await axios.get(`http://localhost:1337/categories?slug=${slug}`);
console.log(response.data[0]) // here when I logged response data it returened a json object
if (!response.data.length) {
return {
statusCode: 404,
};
}
return {
statusCode: 200,
category: response.data[0],
};
};
请问有什么建议吗? 我花了 4 天时间在 Internet 上搜索,但大多数教程都解释了如何获取 static 道具而没有任何关于服务器端道具的详细信息,或者我应该迁移到使用Vue Nuxtjs
,因为它更容易处理这些请求。
您可以从getServerSideProps
上下文访问slug
参数,并直接从那里进行外部 API 调用。 无需从客户端发出请求。
export async function getServerSideProps({ params }) {
// Call external API from here directly
const response = await fetch(`http://localhost:1337/categories?slug=${params.slug}`)
const data = await res.json()
return {
props: { menuItems: data }
}
}
您不能通过调用这样的方法来调用您的 api,api 正在您的服务器上运行,而您正在尝试在客户端对其进行控制台。 唯一可以做到这一点的方法是使用getServerSideProps
或其他选项,如 nextApiRequests。
而是直接在getServerSideProps
中使用你的获取,它会工作得很好。
我建议您阅读此https://nextjs.org/learn/basics/api-routes/api-routes-details以更好地理解它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.