【问题标题】:Why is my function not rendering inside another NextJs page?为什么我的函数没有在另一个 NextJs 页面中呈现?
【发布时间】:2022-07-11 23:02:39
【问题描述】:

我正在构建一个 NextJs 应用程序,但由于某种原因,我没有从页面“Feed.tsx”获取函数以在“Index.tsx”中呈现。但是,当我导航到“/feed”时,该功能会完美呈现。这是为什么呢?

Feed.tsx

import Post from "../components/Post";

function PostList({ posts }){
  return( <>
    {posts?.map((post) => {
      return(
      <div key={post.id}>
        <Post post={post}/>
      </div>
      )
    })}
  </>
  )
}
export default PostList


export async function getServerSideProps(){
  const response = await fetch('http://localhost:3000/posts/')
  if (!response.ok) {
    const message = `An error occured: ${response.statusText}`;
    window.alert(message);
    return;
  }
  const data = await response.json();
  console.log(data);
  
  return{
    props:{
      posts: data,
    },
}
}

index.tsx

import Create from "./create";
import PostList from "./feed";

const Home = () => {
return(
    <div>
        <h1 className="text-blue absolute inset-y-7 left-7 text-xl font-semibold mb-20">Home</h1>
        <Create />
        <PostList />
    </div>
);}

export default Home

【问题讨论】:

  • PostList 是一个页面,而不是一个组件。所以你不能在另一个页面中使用它

标签: reactjs next.js react-component getserversideprops


【解决方案1】:

getServerSideProps()可以触发only with pages而不是组件,getServerSideProps只能从页面导出。

如果您想创建一个从 API 数据中获取的组件,您可以使用useSWR library 创建它。

import Post from "../components/Post";
import useSWR from 'swr'

function PostList(){
//data can be fetched only from API
const { data: posts, error: errorPosts } = useSWR('/api/posts', fetcher)

if (errorPosts ) return <div>failed to load</div>
if (!posts) return <div>loading...</div>

return( <>
    {posts?.map((post) => {
      return(
      <div key={post.id}>
        <Post post={post}/>
      </div>
      )
    })}
  </>
  )
}
export default PostList

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2021-12-09
    • 2023-04-07
    • 2022-11-23
    • 2010-10-13
    • 2011-09-20
    • 2022-01-16
    相关资源
    最近更新 更多