如何解决Next.js中的“TypeError:useOptimistic only works in Client Components”(TypeError:useOptimistic only works in Client Components)

eeq64g8w  于 12个月前  发布在  SEO
关注(0)|答案(1)|浏览(231)

我尝试在我的Next.js页面中使用useOptimistic钩子,并且我已经按照错误消息的建议在我的文件顶部添加了“use client”指令。但是,我仍然遇到错误:

TypeError: useOptimistic only works in Client Components. Add the "use client" directive at the top of the file to use it.

字符串
下面是我的代码片段:

"use client";

import { useEffect, useState } from "react";
import Header from "../components/Header";
import { useOptimistic } from "react";

function Categories() {
  const [categories, setCategories] = useState([]);
  const [optimisticCategories, addOptimisticCategory] = useOptimistic(
    categories,
    (state, newCategory: string) => [...state, { category: newCategory }]
  );

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch("/api/categories");
      const data = await res.json();
      setCategories(data);
    };

    fetchData();
  }, []);

  return (
    <main className="m-8">
      <Header />
    </main>
  );
}

export default Categories;


“下一页”:“^13.5.4”
我已经阅读了Next.js上的文档,但我仍然面临这个问题。任何关于如何解决这个错误的见解都将不胜感激。谢谢!

kx5bkwkv

kx5bkwkv1#

我发现useOptimistic只适用于应用路由器,我试图使用它与旧的页面路由器。

相关问题