在nextjs 13(应用程序目录)上获取API时出错?

iq3niunx  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(151)

我试图从无头CMS(strapi)获取数据,但我一直得到错误“错误:_hooks_useFetch__WEBPACK_IMPORTED_MODULE_2___default(...)不是Data.js中的函数”有人能帮助我理解这里的代码有什么问题吗?
src/app/page.js

import React from "react";
import Data from "../ui/Data";

export default function Home() {
  return (
    <div>
      <main>
        <Data />
      </main>
    </div>
  );
}

src/ui/Data.js

import ItemHomeUI from "./ItemHomeUI";
import useFetch from "../hooks/useFetch";

export default async function Data() {
  const data = await useFetch(
    process.env.NEXT_PUBLIC_API_URL + "?populate=*&filters[type][$eq]=trending"
  );
  return (
    <section>
      <div>
        {data.map((item) => {
          return <ItemHomeUI item={item} key={item.id} />;
        })}
      </div>
    </section>
  );
}

src/hooks/useFetch.js

async function useFetch(url) {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error("failed");
  }
  return res.json();
}
uqcuzwp8

uqcuzwp81#

尝试重命名useFetch函数,以将其与自定义钩子区分开来,因为服务器组件不支持钩子。
src/ui/Data.js

import ItemHomeUI from "./ItemHomeUI";

async function fetchData(url) {
 const res = await fetch(url);
  if (!res.ok) {
    throw new Error("failed");
  }
  return res.json();
}

export default async function Data() {
  const data = await fetchData(
    process.env.NEXT_PUBLIC_API_URL + "?populate=*&filters[type][$eq]=trending"
  );
  return (
    <section>
      <div>
        {data.map((item) => {
          return <ItemHomeUI item={item} key={item.id} />;
        })}
      </div>
    </section>
  );
}

相关问题