[英]Next.js with Typescript: Invalid hook call. Hooks can only be called inside of the body of a function component
[英]Error: Invalid hook call. | Problem to fetch data using context inside of getStaticProps (Next.js)
我是 react/next 的新手,我正在嘗試使用 getStaticProps 加載我的帖子,問題是如果我使用“useAppContext”甚至“useContext(AppContext)”
錯誤 - 錯誤:無效的掛鈎調用。 鈎子只能在 function 組件的內部調用。 這可能由於以下原因之一而發生:
- 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 你可能違反了 Hooks 規則
- 你可能在同一個應用程序中有多個 React 副本
如果我在我的 function 組件的主體內部使用這個“useContext”,它確實會正確加載,但我如何才能在我的 getStaticProps function 上檢索帖子的 ID?
我的實際代碼:
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
}
}
因為我找不到在 getStaticProps 中使用上下文的方法,所以我改變了處理 get 請求的方式——現在我不再使用帖子 ID (postNid),而是使用 slug(例如 /using-multiple-deploy-keys)來查詢帖子的完整數據。 因為我不再使用上下文,所以我能夠使用 getStaticProps 來獲取數據。
作為參考,3 月 10 日此處的提交 ( https://github.com/jonas-gerosa361/jonasdev/commits/main ) 詳細介紹了此更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.