【发布时间】:2021-03-02 23:25:15
【问题描述】:
我正在尝试使用随机状态初始化我的 React 应用程序,但在开发 I realized that React.StrictMode will try to render your component twice 以查找错误时。这会导致控制台的初始打印与屏幕上实际打印的不同。
我是在正确使用 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')
);
【问题讨论】:
-
那么您的实际问题是如何确保页面上打印的内容与严格模式下控制台中的打印内容相匹配?我的意思是最终目标是什么?
-
@codemonkey 两者。我希望它们匹配,但我觉得 StrictMode 产生的不同结果意味着我做错了什么,但我不明白是什么。
标签: javascript reactjs create-react-app