首页 > 解决方案 > 如何将我的 API 函数导入另一个 Typescript 文件?

问题描述

我有一个正在工作的函数,它从我的 API 获取数据,但是当我尝试在其他文件中导入该函数时它不起作用,这可能与 TypeScript 类型有关,但我不知道如何修复它。

这是获取 API 信息的函数:

import { InferGetStaticPropsType } from "next";

type Post = {
  project: string;
};

export const getStaticProps = async () => {
  const res = await fetch("http://localhost:3100/");
  const posts: Post[] = await res.json();

  return {
    props: {
      posts,
    },
  };
};

function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
  return (
    <>
      <h3>Hi</h3>
      {console.log(posts)}
    </>
  );
}

export default Blog;

我试图Blog在我的根 index.tsx 文件中调用上面的代码:

import type { NextPage } from "next";

import Blog from "./blog";

const Home: NextPage = () => {
  return (
    <>
      <Blog />
    </>
  );
};

export default Home;

这是错误:在此处输入图像描述

如果有人想在这里查看整个代码,API 就在express-api文件夹中。

标签: typescripttypesnext.js

解决方案


getStaticProps仅适用于页面。因此,如果您的Blog组件不是页面,则不会调用它。

但是,您可以将获取的数据移动到您的Home页面,然后将其传递给Blog组件:

import { NextPage, InferGetStaticPropsType } from "next";
import Blog from "./blog";

type Post = {
  project: string;
};

export const getStaticProps = async () => {
  const res = await fetch("http://localhost:3100/");
  const posts: Post[] = await res.json();

  return {
    props: {
      posts,
    },
  };
};

const Home: NextPage = ({ posts }: InferGetStaticPropsType<typeof getStaticProps>) => {
  return (
    <>
      <Blog posts={posts} />
    </>
  );
};

export default Home;
function Blog({ posts }) {
  return (
    <>
      <h3>Hi</h3>
      {console.log(posts)}
    </>
  );
}

export default Blog;

推荐阅读