簡體   English   中英

如何從 if 語句 Reactjs 重定向到另一個頁面

[英]How to redirect to another page from an if statement Reactjs

我正在創建一個虛擬 waldo 游戲,您必須在其中找到圖像中的角色。

我正在努力做到這一點,以便當游戲結束並運行 if 語句時,它會轉到另一個頁面,顯示游戲結束。 我嘗試了多種方法來解決這個問題,例如使用 react-router-dom 庫中的 history.push 或 Navigate,但我不知道如何讓它工作

const Game = (props) => {
    const handleClickOption = (e) => {
        if (whichTarget.current === e.target.textContent.toLowerCase()) {
            if (e.target.textContent === 'Waldo') {
                setWaldoStyle(true);
            }
            if (e.target.textContent === 'Odlaw') {
                setOdlawStyle(true);
            }
            if (e.target.textContent === 'Wizard') {
                setWizardStyle(true)
            }
            console.log(e.target.textContent + ' found');
            hit.current += 1

            console.log('this is hit' + hit.current);
            if (hit.current === 3) {
                //function to reset and end game
                console.log("running game over code");
                props.history.push('/gameover');
                console.log('gameover code after navigate');
            }
        }
        
        setRender(!render);
    }
    return (
        <div id="gamePage">
            <div id="stopwatch">{hour.current}:{minute.current}:{second.current}</div>
            <div id="gameBoard">
                <img id="gameBackground" src={gameBackground} alt="gameboard" onClick={handleClickTrue} onLoad={startTimer}></img>
                <div id="waldo" className="hitBox" onClick={handleClickOnTarget}></div>
                <div id="odlaw" className="hitBox" onClick={handleClickOnTarget}></div>
                <div id="wizard" className="hitBox" onClick={handleClickOnTarget}></div>
                <div id="popupContainer">
            </div>
                {render ? <Popup close={handleClickOption} coords={translate} colorWaldo={waldoStyle} colorOdlaw={odlawStyle} colorWizard={wizardStyle}/> : null}
            </div>
            <button onClick={stopTimer}>BREAK</button>
        </div>
    )
}

如果您想在用戶丟失時將用戶重定向到另一個頁面,您可以使用:

if (hit.current === 3) {
   //function to reset and end game
   console.log("running game over code");
   window.location = "./gameover";
   console.log('gameover code after navigate');
}

我不確定你在使用props.history.push()時收到了什么錯誤,我只能假設history道具沒有傳遞給你的組件(這可能是因為你的路由器是如何設置的)。

在任何情況下,使用window.location意味着直接使用瀏覽器 API 並在 React Router 上下文之外執行操作。 如果你想充分使用這個庫,但不確定如何訪問history屬性進行導航,你總是可以通過使用他們提供的useHistory鈎子來獲得它:

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM