更新时间:2022-12-11 09:50:45
我将重写此代码,如下所示:
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
不需要调用setState
;让它只返回值。useState
可以将该值用作其初始状态。
还要澄清一下:useState
只被调用一次。如果希望coin
具有不同的值,则使用此安装程序执行此操作的方法是重新装入组件(重新加载页面)。