reactjs - 警告:无效的 Hook 调用。只有在函数组件体内部才能调用 Hook,当 MDXRemote 执行时
我正在使用 Next.js 和 next-mdx-remote 来构建博客静态网站。
/src/app/blog/post/post1import dynamic from 'next/dynamic';
import { getPostBySlug } from '@/lib/mdx';
import MDXComponents from '@/components/mdx-components';
const MDXRemote = dynamic(() => import('next-mdx-remote').then(mod => mod.MDXRemote), {
ssr: false,
});
export default async function BlogPost() {
const slug = 'post1';
const { mdxSource, frontMatter } = await getPost(slug);
if (!mdxSource) {
return <div>404 - maaz here</div>;
}
return (
<div>
<h1>{frontMatter.title}</h1>
<MDXRemote {...mdxSource} components={MDXComponents} />
</div>
);
}
由于这个 MDXRemote { 警告:无效的 Hook 调用。Hook 只能在函数组件的主体内部调用。这可能是以下原因之一导致的:
- 你可能使用了不匹配的 React 和渲染器(例如 React DOM)版本
- 你可能违反了 Hooks 规则
- 你可能在同一个应用中有多个 React 副本 } 当我注释掉这个 MDXRemote 时,这个错误就消失了
在上面的代码中,我使用了 getPost,它位于 /src/lib/mdx.tsx,这个函数如下
export const getPost = async (slug: string) => {
const filePath = path.join(contentDir, `${slug}.mdx`);
try {
const source = fs.readFileSync(filePath, 'utf8');
const { content, data } = matter(source);
const mdxSource = await serialize(content);
return { mdxSource, frontMatter: data };
} catch (error) {
console.error('Error reading file:', error);
return { mdxSource: null, frontMatter: null };
}
};
那么,请告诉我上述错误的主要原因。我尝试了很多方法使用 getStaticProps() 来解决这个问题,但 nextjs 13 版本在 /app 目录中不适用,所以这也会报错
我正在尝试将 mdx 文件转换为 React 组件,并在我的网站中使用 serialize 和 MDXRemote,但出现此错误 警告:无效的 Hook 调用。Hooks 只能在函数组件的主体内调用。这可能是以下原因之一导致的:
- 你可能使用了不匹配的 React 和渲染器(例如 React DOM)版本
- 你可能违反了 Hooks 规则
- 您在同一个应用中可能有多个 React 副本。请参阅 https://reactjs.org/link/invalid-hook-call 获取有关如何调试和修复此问题的提示。⨯ 内部错误:TypeError:无法读取 null 的属性(读取 'useState')
答案#1
您正在使用不需要 serialize 的应用程序目录,并且应该从 next-mdx-remote/rsc 导入,请查看其文档中标题为 “React 服务器组件(RSC)与 Next.js 应用目录支持” 的部分