[英]How can I set a randomized initial state using a conditional and React Hooks?
This example simulates a coin toss.此示例模拟抛硬币。
I would like to randomize the initial state of the coin.我想随机化硬币的初始状态。 The first time the page is loaded it could show heads.第一次加载页面时,它可能会显示头像。 The next time, tails.下一次,尾巴。 To do so, I am using a random number generated by the Math method and a conditional to determine the face of the coin based on the random number (even number shows heads, odd shows tails).为此,我使用 Math 方法生成的随机数和一个条件来根据随机数确定硬币的正面(偶数表示正面,奇数表示反面)。
The value needs to be displayed upon the initial render.该值需要在初始渲染时显示。
I also want to store the value in state using React's Hooks to use later in my app.我还想使用 React 的 Hooks 将值存储在状态中,以便稍后在我的应用程序中使用。 How can I set a randomized initial state value using hooks?如何使用钩子设置随机初始状态值?
Here is the code that I am working with.这是我正在使用的代码。 It currently does not function and I'm not sure what I am doing incorrectly to achieve my goal:它目前不起作用,我不确定我在做什么不正确来实现我的目标:
import React, { useState } from 'react';
import './App.css';
function App() {
const [coin, setCoin] = useState(randomizePlayer())
const randomizePlayer = () => {
let number = Math.floor(Math.random() * 10) + 1
return (number % 2 === 0) ? setCoin('Heads') : setCoin('Tails')
}
return (
<div className="App">
The coin is showing {coin}
</div>
);
}
export default App;
I'm brand new to the hooks API and am using this exercise to learn.我是 hooks API 的新手,正在使用这个练习来学习。
Any help is appreciated!任何帮助表示赞赏!
I would rewrite this code as follows:我将重写这段代码如下:
const randomizePlayer = () => {
const number = Math.floor(Math.random() * 10) + 1
return (number % 2 === 0) ? 'Heads' : 'Tails'
}
function App() {
const [coin, setCoin] = useState(randomizePlayer())
return (
<div className="App">
The coin is showing {coin}
</div>
);
}
randomizePlayer
does not need to call setState
; randomizePlayer
不需要调用setState
; let it just return a value.让它只返回一个值。 useState
can use that value as its initial state. useState
可以使用该值作为其初始状态。
Also to clarify: useState
gets called just once.还要澄清一下: useState
只被调用一次。 If you want coin
to have a different value, the way to do that with this setup is to remount the component (reload the page).如果您希望coin
具有不同的值,使用此设置的方法是重新安装组件(重新加载页面)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.