简体   繁体   English

Next.js: router.push 不刷新页面

[英]Next.js : router.push not refreshing the page

I'm building a next.js page /page/data/[dataId] (this page is navigated when A user clicks on a link from page /page/data , I fetch the list of items through an API ).我正在构建一个 next.js 页面/page/data/[dataId] (当用户单击来自页面/page/data的链接时导航此页面,我通过 API 获取项目列表)。

When user clicks on a button, I call an API to delete this item from DB.当用户点击一个按钮时,我调用 API 从数据库中删除这个项目。 Once the API call is successful.一旦API调用成功。 I need to redirect user back to /page/data page.我需要将用户重定向回/page/data页面。 Here's how I'm doing it:我是这样做的:

 async function removeData(){

    // ... some logic

    await removeData({input});
    setTimeout(()=>{
          router.push("/page/data"); // redirecting to parent
     },2000)

}

Once the user is redirected back to /page/data/ I need to refresh the list of data items bacause I want to remove the item which got deleted.一旦用户被重定向回/page/data/我需要刷新数据项列表因为我想删除被删除的项目。 Now the problem is - The /page/data/ is not getting refreshed after navigating it through router.push .现在的问题是 - /page/data/在通过router.push导航后没有得到刷新。

I know we can achieve this by replacing router.push to window.location="/page/data" but that is very expensive way.我知道我们可以通过将router.push替换为window.location="/page/data"来实现这一点,但这是非常昂贵的方式。

I also tried:我也试过:

router.push("/page/data",undefined,{shallow:false})

but it didn't work.但它没有用。

Anyone can you help me how can we achieve this in optimal way?任何人都可以帮助我如何以最佳方式实现这一目标? I find window.location approach too expensive.我发现window.location方法太贵了。

After deleting an item from DB you can try to update your local data instead of fetching it from the server从数据库中删除项目后,您可以尝试更新本地数据而不是从服务器获取它

I have used this method in the past, like you say it may be an expensive approach but it keeps the routing without 'next router' compared to moving part of the routing to window.location .我过去曾使用过这种方法,就像您说的那样,这可能是一种昂贵的方法,但与将部分路由移动到window.location相比,它可以在没有“下一个路由器”的情况下保持路由。

router.push('ROUTE').then(() => window.location.reload())

Next router also has a reload function that could be called, but it still uses the principles of after the route. Next router 也有一个可以调用的 reload 函数,但它仍然使用 after route 的原理。

router.push('ROUTE').then(() => router.reload())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM