javascript 我可以通过onClick更改getServerSideProps获取URL吗

ilmyapht  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(178)

我想更改获取URL,但找不到答案。例如,我想更改我的let page并刷新getServerSideProps,以便通过单击按钮重新呈现所有新闻。
我可以这样做,还是我需要另一种方法?

import Head from "next/head";
import { NewsArticle, NewsResponse } from "@/modules/NewsArticles";
import { GetServerSideProps } from "next";
import NewsArticleGrid from "@/components/NewsArticleGrid";
import { Button } from "react-bootstrap";
import { useRouter } from "next/router";

interface BreakingNewsPageProps {
  newsArticles: NewsArticle[];
}

let page =
  "https://newsapi.org/v2/everything?q=apple&from=2023-05-03&to=2023-05-03&sortBy=popularity&apiKey=";

export const getServerSideProps: GetServerSideProps<BreakingNewsPageProps> = async () => {
  const response = await fetch(page + process.env.NEWS_API_KEY);
  const newsResponse: NewsResponse = await response.json();
  return {
    props: { newsArticles: newsResponse.articles },
  };
};

export default function BreakingNewsPage({ newsArticles }: BreakingNewsPageProps) {
  const router = useRouter();

  return (
    <>
      <Head>
        <title>Breaking news </title>
      </Head>
      <main>
        <h1>Breaking News</h1>
        <Button
          onClick={() => {
            page =
              "https://newsapi.org/v2/everything?q=tesla&from=2023-04-03&sortBy=publishedAt&apiKey=";
            console.log(page);
            router.push(router.asPath);
          }}
        >
          Change url
        </Button>
        <NewsArticleGrid articles={newsArticles} />
      </main>
    </>
  );
}
bvn4nwqk

bvn4nwqk1#

您在getServerSideProps中使用的这个page变量只存在于服务器上。它将无法在浏览器上访问,而您的按钮单击处理程序将在浏览器上运行。
您可以使用发送到getServerSideProps的查询字符串进行刷新。下面是一个类似的例子,点击后获取新帖子:

// pages/index.js

import { useRouter } from "next/router";

export default function Home({ post }) {
  const router = useRouter();
  return (
    <>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      <button
        onClick={() => {
          router.push({
            href: router.pathname,
            query: { page: Math.round(Math.random() * 10) },
          });
        }}
      >
        Fetch another random post
      </button>
    </>
  );
}

const defaultPage = 1;

export const getServerSideProps = async (context) => {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts/" + (context.query.page || defaultPage));
  const data = await response.json();
  return {
    props: { post: data },
  };
};

我使用jsonplaceholder API使它在复制-粘贴后可以轻松地为任何人工作。

相关问题