【问题标题】:How to initialize random state when using React?使用 React 时如何初始化随机状态?
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 2019-01-04
    • 2019-09-02
    • 1970-01-01
    • 2019-04-12
    • 2018-04-06
    • 1970-01-01
    • 2019-10-30
    • 2019-10-05
    相关资源
    最近更新 更多