我想更改获取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>
    </>
  );
}

推荐答案

您在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 },
  };
};

我使用了jsonplaceholderAPI,以便在复制粘贴后可以轻松地为任何人工作.

Javascript相关问答推荐

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

通过嵌套模型对象进行Mongoose搜索

Phaser 3 console. log()特定游戏角色的瓷砖属性

Angular 17—每当一个布尔变量变为真时触发循环轮询,只要它保持为真

使用LocaleCompare()进行排序时,首先使用大写字母

如何在JavaScript文件中使用Json文件

在open shadow—root中匹配时,使用jQuery删除一个封闭的div类

我可以使用使用node.js创建的本地主机来存储我网站上提交的所有数据吗?没有SQL或任何数据库.只有HTML语言

Reaction Redux&Quot;在派单错误中检测到状态Mutations

OpenAI转录API错误请求

有没有一种直接的方法可以深度嵌套在一个JavaScript对象中?

匹配一个或多个可选重复的特定模式

在渲染turbo流之后滚动到元素

通过跳过某些元素的对象进行映射

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

Socket.IO在刷新页面时执行函数两次

我在哪里添加过滤器值到这个函数?

我们是否可以在reactjs中创建多个同名的路由

JS/css:将数字输入的S函数和可调整大小的元素S函数绑定在一起

正在发出错误的URL请求