使用React时如何初始化随机状态?



我试图用随机状态初始化我的React应用程序,但在开发时我意识到React。StrictMode会尝试渲染你的组件两次,以便找到bug。这将导致初始打印到控制台的内容与实际打印到屏幕上的内容不同。

我是否正确使用useState或React告诉我做其他事情?

代码:
App.js

export function Game(props) {
const [theSecret, _] = useState(
Array(4)
.fill()
.map(() => getRandomInt(4))
);
console.log(theSecret)
return <button>{theSecret}</button>
}

index.js

ReactDOM.render(
<React.StrictMode>
<Game />
</React.StrictMode>,
document.getElementById('root')
);

在这种情况下,您应该使用useState延迟初始化

export function Game(props) {
const [theSecret, _] = useState(() =>
Array(4)
.fill()
.map(() => getRandomInt(4))
);
console.log(theSecret)
return <button>{theSecret}</button>
}

它将防止在每次渲染中生成随机值

最新更新