javascript - 当值相等时,React hooks useState setValue 仍然会重新渲染一次

标签 javascript reactjs frontend react-hooks

我有下面的示例代码:

function App() {
  console.log("render");
  const [val, setVal] = React.useState(0);
  return (
    <div className="App">
      <h1>{val}</h1>
      <button onClick={() => setVal(12)}>Update with same value</button>
    </div>
  );
}

当我多次单击一个按钮时,控制台会记录 3 次“渲染”消息。对我来说,应该只有 2 次:

  • 第一次渲染 1

  • 2 用于从 val 0 更新到 12(单击按钮时)

从这一次开始,它不应该重新渲染,因为相同的值 (12) 已更新为 val。

但是为什么会出现3次呢?这意味着尽管更新了相同的值,它仍然会重新渲染一次。

请知道的 friend 解释一下,谢谢

P/S:我发现它只会在值更改然后更新为相同值时导致额外的重新渲染

function App() {
  console.log("render");
  const [val, setVal] = useState(4);
  return (
    <div className="App">
      <h1>{val}</h1>
      <button onClick={() => {
        setVal(val => val + 1)
      }}>Update</button>
      <button onClick={() => {
        setVal(val => val)
      }}>Update with same value</button>
    </div>
  );
}

当第一次点击第二个按钮时,没有重新渲染调用,但是如果你点击第一个按钮然后第二个按钮,第二个按钮会导致 1 次额外的重新渲染

最佳答案

此线程可能对您有所帮助:React: Re-Rendering on Setting State - Hooks vs. this.setState

此外,您可以查看 here 上的第二段其中说:

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

关于javascript - 当值相等时,React hooks useState setValue 仍然会重新渲染一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57652176/

相关文章:

javascript - Marionette Js 扩展底座 Controller

javascript - d3 localStorage 比较数组.filter CoffeeScript ;数组变量不起作用

javascript - hyperHTML电线与字符串

Javascript 到 Excel : bad performance for lack of "range" method

reactjs - 增加超时限制 gatsby-source-wordpress-experimental

javascript - 为什么我的 React Bootstrap Glyphicons 没有显示?

javascript - Joomla 脚本中的菜单悬停效果

javascript - 类型错误 : dispatch is not a function

javascript - 似乎无法从 D3js 工作中获取示例?

html - 如何消除网页上 iPhone 缺口处的空白