typescript - 如何将我的 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
文件夹中。
解决方案
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;
推荐阅读
- reactjs - 在 Android 的 React Native 项目中对齐文本
- python - 运行 sklearn KNN 预测时程序停止
- python - 如何保留带有交换项目的字典副本?
- amazon-web-services - 只有 SQS 和 Lambda 的 AWS SAM
- flutter - video_player:如何抑制 TCP 输出
- xamarin - 全新项目上的 Xamarin.Forms 错误?
- linux - 检查特定列中的值在下一行的同一列中是否相同?
- c# - 函数 get_Range 是否允许当前工作表之外的范围?
- java - Firebase Cloud Firestore - 从偶数个段中获取集合
- groovy - Jmeter Groovy如何用{替换这个字符串