我想更改获取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>
</>
);
}
1条答案
按热度按时间bvn4nwqk1#
您在
getServerSideProps
中使用的这个page
变量只存在于服务器上。它将无法在浏览器上访问,而您的按钮单击处理程序将在浏览器上运行。您可以使用发送到
getServerSideProps
的查询字符串进行刷新。下面是一个类似的例子,点击后获取新帖子:我使用
jsonplaceholder
API使它在复制-粘贴后可以轻松地为任何人工作。