当值相等时,React 钩子 useState setValue 仍然重新渲染一次 [英] React hooks useState setValue still rerender one more time when value is equal
问题描述
我有以下示例代码:
function App() {console.log("渲染");const [val, setVal] = React.useState(0);返回 (<div className="应用程序"><h1>{val}</h1><button onClick={() =>setVal(12)}>使用相同的值更新</button>
);}
当我多次单击一个按钮时,控制台会记录 3 次并显示render"消息.对我来说,应该只有 2 次:
1 表示第一次渲染
2 用于从 val 0 到 12 的更新(单击按钮时)
从这一次开始,它不应重新渲染,因为相同的值 (12) 已更新为 val.
但是为什么会出现3次呢?这意味着尽管更新了相同的值,它仍然会重新渲染一次.
谁知道请解释一下,在此先感谢.
P/S:我发现它只会在更改值然后用相同的值更新时导致额外的重新渲染
function App() {console.log("渲染");const [val, setVal] = useState(4);返回 (<div className="应用程序"><h1>{val}</h1><button onClick={() =>{setVal(val => val + 1)}}>更新</按钮><button onClick={() =>{setVal(val => val)}}>使用相同的值更新</button>
);}
当第一次点击第二个按钮时,没有重新渲染调用,但是如果你点击第一个按钮然后第二个按钮,第二个按钮会导致 1 次额外的重新渲染
此主题可能对您有所帮助:React:重新渲染设置状态 - Hooks 与 this.setState
此外,您可以查看 here 上面写着:
<块引用>请注意,在退出之前,React 可能仍需要再次渲染该特定组件.这不应该是一个问题,因为 React 不会不必要地深入"到树中.如果您在渲染时进行昂贵的计算,您可以使用 useMemo 对其进行优化.
I have sample code below:
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>
);
}
When I click a button multiple times, the console log 3 times with 'render' message. For me, it should be 2 times only:
1 for first render
2 for the update from val 0 to 12 (when click button)
and since this time, it should not re-render because the same value (12) is updated to val.
But why it appears 3 times? That mean it still re-render one more time despite the same value was updated.
Anyone who know please explain this, thanks in advance.
P/S: I've figured out that it's only cause an extra re-render when the value changed then has been updated with the same
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>
);
}
When first click on 2nd button, no re-render call, but if you click the 1st button then 2nd button, 2nd button cause 1 extra re-render
This thread may help you : React: Re-Rendering on Setting State - Hooks vs. this.setState
Also, you can check the second paragraph over here which says:
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.
这篇关于当值相等时,React 钩子 useState setValue 仍然重新渲染一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!