[英]Error: Invalid hook call. | Problem to fetch data using context inside of getStaticProps (Next.js)
I'm new to react/next and I'm trying to load my post with getStaticProps, the problem is if I use the "useAppContext" or even "useContext(AppContext)"我是 react/next 的新手,我正在尝试使用 getStaticProps 加载我的帖子,问题是如果我使用“useAppContext”甚至“useContext(AppContext)”
error - Error: Invalid hook call.
错误 - 错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.
钩子只能在 function 组件的内部调用。 This could happen for one of the following reasons:
这可能由于以下原因之一而发生:
- You might have mismatching versions of React and the renderer (such as React DOM)
您可能有不匹配的 React 版本和渲染器(例如 React DOM)
- You might be breaking the Rules of Hooks
你可能违反了 Hooks 规则
- You might have more than one copy of React in the same app
你可能在同一个应用程序中有多个 React 副本
If I use this "useContext" inside of the body of my function component it indeed loads correctly but how could I retrieve the id of the post on my getStaticProps function?如果我在我的 function 组件的主体内部使用这个“useContext”,它确实会正确加载,但我如何才能在我的 getStaticProps function 上检索帖子的 ID?
My actual code:我的实际代码:
import { GetStaticPaths, GetStaticProps } from 'next';
import { useAppContext } from '../../context/AppContext';
interface PostProps {
post: {
field_body: string,
field_description: string,
field_posts_tags: string,
nid: string,
title: string,
field_readingtime: string
}
}
export default function PostTemplate({post}: PostProps) {
console.log(post);
return (
<h2>test</h2>
)
}
export const getStaticPaths: GetStaticPaths = async() => {
return {
paths: [],
fallback: true
}
}
export const getStaticProps: GetStaticProps = async () => {
const value = useAppContext();
const postNid = value.postNid;
const post = await fetch(`https://cms.jonasdev.com.br/api/posts/get/${postNid}`)
.then(response => response.json())
.then(response => response[0])
return {
props: {
post
},
revalidate: 60 * 60 * 24 //24h
}
}
Since I could not find a way to use context inside of getStaticProps I changed how I handle the get request - now I'm no longer using the post id (postNid) but the slug (eg /using-multiple-deploy-keys) to query the full data of the post.因为我找不到在 getStaticProps 中使用上下文的方法,所以我改变了处理 get 请求的方式——现在我不再使用帖子 ID (postNid),而是使用 slug(例如 /using-multiple-deploy-keys)来查询帖子的完整数据。 Since I'm no longer using context I was able to use getStaticProps to fetch the data.
因为我不再使用上下文,所以我能够使用 getStaticProps 来获取数据。
For reference, the commits here ( https://github.com/jonas-gerosa361/jonasdev/commits/main ) on March 10th cover this change in detail.作为参考,3 月 10 日此处的提交 ( https://github.com/jonas-gerosa361/jonasdev/commits/main ) 详细介绍了此更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.