【问题标题】:Why does React render the page two times?为什么 React 会渲染页面两次?
【发布时间】:2023-01-24 17:02:36
【问题描述】:

在以下 App.js 的最小工作示例中:

import { useState, useEffect } from "react";


export default function App() {
  const [isShown, setIsShown] = useState(true);
  return (
    <>
      <button onClick = {() => setIsShown(!isShown)}>
        {isShown? 'Hide Counter' : 'Show Counter'}
      </button>
      {isShown? <Counter /> : null}
    </>
  );
}

function Counter(){
  const [count, setCount] = useState(0);
  const [bool, setBool] = useState(false);

  useEffect(() => {
    console.log('render');
  });
  
  useEffect(() => {
      console.log('mounted');
    }, []);
  return (
    <div className="counter">
      <button onClick={() =>setBool(!bool)}>Re-Render</button>
      <button onClick={() =>setCount(count + 1)}>Increment</button>
      <p> Count: {count}</p>
    </div>
  );
}

每当我刷新页面或单击“隐藏计数器”然后单击“显示计数器”时,我都会得到两组 console.logs(即消息“呈现”和“已安装”显示两次)。我的期望是“render”和“show”应该只出现一次。在当前情况下,这似乎意味着每次加载页面时组件都会呈现两次。我已经在 Firefox 和 Chrome 上对此进行了测试,并在两者中发现了相同的行为。

为什么会这样,我该如何开始调试呢?

【问题讨论】:

标签: reactjs


【解决方案1】:

这是因为 React 严格模式,如果你从你的索引文件中删除它,你不会得到两个渲染。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 2020-09-07
    • 2020-11-22
    • 2020-01-03
    • 1970-01-01
    • 2021-07-27
    • 2015-02-25
    相关资源
    最近更新 更多