简体   繁体   中英

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()

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.

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 . use the best practices method to update your state with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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