简体   繁体   English

当用户在 history.push() 之后按下“返回”按钮时,我们可以刷新页面吗

[英]Can we refresh a page when a user presses "go back" button after history.push()

In my react application, i have a button to play a game with history.push()在我的反应应用程序中,我有一个按钮可以用history.push()玩游戏

const handle = () => {
    history.push("/game");
    setPlayer({...player, inLobby: false, inGame: true});
};

<button onClick={handle}>
    Play !
</button>

In game, i have a prompt that warn the user when he presses go back and refresh button.在游戏中,我有一个提示,当他按下返回刷新按钮时警告用户。

<Route path="/lobby">
    {player.inLobby ? <Lobby/> : <Redirect to="/"/> }
</Route>
<Route path="/game">
    {player.inGame ? <Play/> : <Redirect to="/"/>}
</Route>

When the user refresh the page, no problem he returns to "/" with the refreshed page.当用户刷新页面时,没有问题,他用刷新的页面返回"/"
But when the user presses the go back button he returns to "/" and the page is not refreshed.但是当用户按下返回按钮时,他返回到"/"并且页面没有刷新。
How do I force the page to refresh?如何强制刷新页面?

您可以使inGameinLobby无效,以便Router执行其逻辑或使用 vanilla javascript location.href = '/'但这将导致丢失活动状态。

You didn't update your player properly in handle function.您没有在handle功能中正确更新您的播放器。

Quick fix快速解决

const handle = () => {
  setPlayer(prevState => (
   {...prevState, inLobby: false, inGame: true}
  ))
  history.push("/game")
}

Explanation解释

Don't use the current state value player to set the setPlayer .不要使用当前状态值player来设置setPlayer use the best practices method to update your state with prevState .使用最佳实践方法通过prevState更新您的状态。

In your case, you need to set the state and then push to another page after that setState , so with a , the history.push will be called after setState在您的情况下,您需要设置状态,然后在setState之后推送到另一个页面,因此使用 a ,将在setState之后调用history.push

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

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