英文:
How to use getStaticProps in typescript in nextJs
问题
I keep getting undefined when i try to get all posts from my backend, what am i doing wrong?
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 }   
   }
}
Isn't this a right way of calling data from an api in next js with typescript?
英文:
I keep getting undefined when i try to get all posts from my backend, what am i doing wrong?
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 }   
   }
 }
Isn't this a right way of calling data from an api in next js with typescript?
答案1
得分: 2
以下是您要翻译的内容:
您需要定义函数返回的数据类型。请看下面的示例,其中包含用户数据。
type UserData = {
  name: string,
  email: string,
  mobile: string
}
type Props = {
  data: UserData;
};
export const getStaticProps: GetStaticProps<Props> = async () => {
  const data: UserData = /* 获取用户数据的逻辑 */;
  return { props: { data } };
};
const Users = (props: Props) => {
  const { data } = props
  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  );
};
export default Users;
英文:
You will require to define the type of data that will be returned by the function. Have a look on the below example with user data.
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论