【问题标题】:Is there any way to reload a page with a button click in next.js?有没有办法通过在 next.js 中单击按钮来重新加载页面?
【发布时间】:2025-12-10 10:35:02
【问题描述】:

我目前正在处理一个 next.js 项目,我应该以某种方式重新加载我的页面以发出新的 API 请求。我是新手,所以我不知道该怎么做。我尝试了一些方法,但没有奏效。这是我的代码,它是一个告诉你随机目的地点的应用程序。

import React from 'react';
import useSWR from "swr";
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

const Profile = function Profile() {
  
  function GetData(){
    const {data,error} = useSWR("https://miras-backend.herokuapp.com/random");
    return {data,error}
  }
  const {data,error} = GetData();
  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return (
  
    
    <Card>
      <CardContent>
        <Typography color="textSecondary" gutterBottom>
          Eserin Adı      
        </Typography>
        <Typography variant="h5" component="h2">
          {data.title}
        </Typography>
        <Typography  color="textSecondary">
          {data.adress}
          <br/>
          <br/>
        </Typography>
        <Typography variant="body2" component="p">
          {data.about}
        </Typography>
      </CardContent>
      <CardActions>
        <Button onClick={()=> {Profile()}}>Sonraki</Button>
      </CardActions>
    </Card>
  );
}

【问题讨论】:

  • 您可能不需要“以某种方式重新加载我的页面以发出新的 API 请求”,几乎可以肯定有一种方法可以在不重新加载页面的情况下发出新请求。请详细描述您的问题
  • 就像 Vencovsky 说的那样,您应该找到一种仅重新加载 api 请求而不是重新加载整个页面的方法。无论如何,重新加载的简单方法是在单击按钮时调用 window.reload()。

标签: javascript reactjs typescript next.js


【解决方案1】:

我认为你的做法不正确,你可以这样做

const Profile = function Profile() {
  
   const {data, error, mutate} = useSWR("https://miras-backend.herokuapp.com/random");
  
  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return (
    
    <Card>
      <CardContent>
         .....
      </CardContent>
      <CardActions>
        <Button onClick={()=> {mutate(); /* <-- this will trigger a reload */}}>Sonraki</Button>
      </CardActions>
    </Card>
  );
}

更新 swr 还公开了一个 revalidate 方法,这是刷新缓存的规范方法。

const Profile = function Profile() {
  
   const {data, error, mutate, revalidate} = useSWR("https://miras-backend.herokuapp.com/random");
  
  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return (
    
    <Card>
      <CardContent>
         .....
      </CardContent>
      <CardActions>
        <Button onClick={()=> {revalidate(); /* <-- this will trigger a reload */}}>Sonraki</Button>
      </CardActions>
    </Card>
  );
}

【讨论】:

    【解决方案2】:
     - let currentLocation = window.origin;   // get url of current page
     - window.location.href = currentLocation // redirect
    

    【讨论】:

      最近更新 更多