无法使Nextjs 12代码在13中工作,出现获取问题

lyr7nygr  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(156)

我试图将我现有的代码从Next js 12转换为13。但是我无法使它工作。我应该如何转换才能使它工作?得到错误,如你不能使用“useState”等。

import { useState } from 'react';
import Head from 'next/head';

import { loadData } from './api/post';
import {
  Section,
  Cover,
  SocialNetworks,
  BuyMeCoffee,
  Title,
  PostGrid,
  Post,
  Button
} from '../components';

const LOAD_MORE_STEP = 4;

export default function Home({ initialPosts, total }) {
  const [ posts, setPosts ] = useState(initialPosts);
  const [ loadedAmount, setLoadedAmount ] = useState(LOAD_MORE_STEP);
  const [ loading, setLoading ] = useState(false);

  const showLoadButton = total > loadedAmount;

  const getMorePosts = async () => {
    setLoading(true);

    try {
      const data = await fetch(`/api/post?start=${loadedAmount}&end=${loadedAmount + LOAD_MORE_STEP}`).then((response) => response.json());
      setLoadedAmount(loadedAmount + LOAD_MORE_STEP);
      setPosts([...posts, ...data.posts])
      setLoading(false);
    } catch (error) {
      console.log(error);
      setLoading(false);
    }
  };

  return (
    <div style={{
      marginBottom: '1rem',
    }}>
      <Head>
        <title>My blog</title>
      </Head>
      <Section>
        <Cover title="Elena<br />Litvinova" />
        <SocialNetworks />
        <BuyMeCoffee />
      </Section>
      <Section>
        <Title>New Post</Title>
        <PostGrid>
          {posts.map((post) => (
            <Post
              key={post._id}
              {...post}
            />
          ))}
        </PostGrid>
        {showLoadButton && (
          <div style={{
            display: 'flex',
            justifyContent: 'center',
          }}>
            <Button
              disabled={loading}
              onClick={getMorePosts}
            >
              Load more posts...
            </Button>
          </div>
        )}
      </Section>
    </div>
  )
}

export async function getServerSideProps() {
  const { posts, total } = await loadData(0, LOAD_MORE_STEP);

  return {
    props: {
      initialPosts: posts,
      total
    },
  }
}
siv3szwd

siv3szwd1#

React钩子仅在客户端可用。如果它是客户端组件,则必须将“use client”添加到文件顶部。在Next.js 13中,所有组件默认为React服务器组件。Here are the docs for server and client components in Next.js
我还建议您使用@tanstack/react-query获取数据。

相关问题