如何在nextJs的typescript中使用getStaticProps



当我试图从我的后端获得所有帖子时,我一直未定义,我做错了什么?

import { AppContext } from '@/helpers/Helpers'
import axios from 'axios'
import { GetStaticProps} from 'next'
import React, {useContext} from 'react'
import Tweet from './Tweet'
import { TweetsContainer } from './Tweets.styled'

export interface IAppProps {
}
export default function Tweets(props: any, { allPosts }: any) {

console.log(allPosts);

return (
<div>
<TweetsContainer>
<div>
</div>
</TweetsContainer>
</div>
);
}
export const getStaticProps: GetStaticProps = async () => {
const res = await axios.get(`http://localhost:7000/api/tweets`)
const data = res.data

return {
props: { allPosts: data }   
}
}

这不是一个正确的方式调用数据从api在next js与typescript?

您需要定义函数将返回的数据类型。看一下下面的用户数据示例。

type UserData = {
name: string,
email: string,
mobile: string
}
type Props = {
data: UserData;
};
export const getStaticProps: GetStaticProps<Props> = async () => {
const data: UserData = /* logic to fetch user data */;
return { props: { data } };
};
const Users = (props: Props) => {
const { data } = props
return (
<div>
<h1>{data.name}</h1>
<p>{data.email}</p>
</div>
);
};
export default Users;

最新更新