在ReactHook中使用Math.random

问题描述 投票:-2回答:1

[我从2-3天开始学习反应,在React Hook的功能组件中使用Math.random()时遇到了一个问题。

让我解释一下:假设我要编写一个游戏,其中生成了一个随机数,用户需要猜测它。我想到了这样的东西:

function App() {
    const [users, setUsers] = useState("")
    let tbg = Math.floor(Math.random()*100)

    const handleSubmit = () => {
        if(users === tbg) {
            alert("Correct")
        }
        else if(users < tbg) {
            alert("More")
        }
        else {
            alert("Less")
        }
    }
  return (
    <div className="App">
      <h2>Guess the number</h2>
        <h3>(for debug=>) the number is : {tbg} </h3>
        <br/>
        <form onSubmit={handleSubmit}>
            <input type="text" value={users} onChange={e => setUsers(e.target.value)} />
        </form>
    </div>
  );
}

问题是每次用户输入字符/数字时,要猜测的数字都会更改。我考虑了将数学随机数放入函数并有条件地执行的解决方案。但是,我想知道是否有更好的“反应挂钩”方法。

谢谢

reactjs random react-hooks
1个回答
0
投票

仅使用useEffect挂钩

    function App () {   
           const [users, setUsers] = useState("")
           const [tbg, setTbg] = useState("")   

           useEffect(() => {
              let number = Math.floor(Math.random()*100)
              setTbg(number);
           }, []);


      }
© www.soinside.com 2019 - 2024. All rights reserved.