我应该在NextJS中等待Router.push吗?

huangapple go评论69阅读模式
英文:

Should I await a Router.push in NextJS

问题

我使用 NextJS 和 import Router from 'next/router'; 我用来在页面间导航的方法是 Router.push('/some-page'); 这个方法是 async 的,但是它可以正常工作,即使我没有添加 await Router.push('/some-page'); 我使用得对吗?我实际上并不想执行此点以下的任何代码,因为我只是在重定向用户。我在官方文档中找不到任何有用的信息。

英文:

I am using NextJS and import Router from 'next/router'; The method that I use to navigate between pages is Router.push('/some-page'); This method is async, yet, it works without me adding an await Router.push('/some-page'); Am I using it correctly? I do not really want to execute any code that is below this point as I am really just redirecting the user. I cannot find anything useful in the official documentation.

答案1

得分: 1

Router.push 方法返回一个 promise,这意味着它是一个异步操作。然而,如果没有代码需要等待导航,你不一定需要在 Router.push 中使用 await。

不等待这个 promise,实质上是在继续执行下一行代码之前不等待导航完成。这在你想要触发导航但同时继续执行后续代码而无需等待导航完成的情况下仍然很有用。

再次强调,如果在你的情况下是调用 push 方法的最后一行代码,那么等不等待返回的 promise 真的无关紧要。

如果你有只有在导航完成后才应该执行的代码,比如更新状态或在新页面上获取数据,那么你需要使用 await 或以不同的方式处理导航完成。

那么什么时候应该等待呢? 如果你有只有在导航完成后才应该执行的代码,比如更新状态或在新页面上获取数据。

英文:

The Router.push method returns a promise, which means it is an asynchronous operation. However, you don't necessarily need to use await with Router.push if you don't have any code that should wait for the navigation

By not awaiting the promise, you are essentially not waiting for the navigation to finish before moving on to the next line of code. This still can be useful in scenarios where you want to trigger a navigation while also continuing to execute subsequent code without waiting for the navigation to complete.

Again if in your case it's the last line of code where you're calling the push method, then it really doesn't matter if you await or not the returned promise

If you have code that should only execute after the navigation is complete, such as updating state or fetching data on the new page, then you would need to use await or handle the navigation completion in a different way.

So when should you wait? If you have code that should only execute after the navigation is complete, such as updating state or fetching data on the new page

huangapple
  • 本文由 发表于 2023年6月18日 23:03:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定