我目前正在研究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>
);
}
答案 0 :(得分: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>
);
}
答案 1 :(得分:0)
- let currentLocation = window.origin; // get url of current page
- window.location.href = currentLocation // redirect