使用钩子设置具有相同值的状态会导致重新渲染吗? [英] Set state with same value using hooks will cause a rerender?
问题描述
使用钩子,如果我使用与 state
相同的值调用 setState
,它会重新渲染组件吗?
如果是,我该如何避免?
例如
const [state, setState] = useState(foo)...//代码中的任意位置设置状态(富)
考虑到 foo
可以是任何东西,例如 {}
、true
、props.bar
或组件外部的变量(常量).
如果您使用相同的值调用 setState
,它不会重新渲染组件.
试试这个:
import React, { useState, useEffect } from "react";const foo = { foo: 'bar' };导出默认值({名称})=>{const [state, setState] = useState(foo);console.log("渲染!");useEffect(() => {设置状态(富);console.log("状态重置!");});const handleClick = () =>{console.log("handleClick!");设置状态(富);//setState({ ...foo, bar : 'baz' });}返回 (<div><h1>你好{name}!</h1><button onClick={handleClick}>点击我</button>
);};
您会注意到,即使单击该按钮,该值也没有改变.它不是重新渲染组件.如果您更改用于调用 setState
的参数,它将重新渲染组件.
这是一个代码示例 供您参考.
尝试在 handleClick
方法中注释第一个 setState
并取消注释第二个以查看差异.
Using hooks, If I call setState
with the same value as the state
, will it rerender the component?
If yes, how can I avoid that?
e.g.
const [state, setState] = useState(foo)
...
// any where in the code
setState(foo)
Considering that foo
can be any thing, such as {}
, true
, props.bar
or a variable from out side of the component (constant).
It won't re-render the component if you call setState
with the same value.
Try this out:
import React, { useState, useEffect } from "react";
const foo = { foo: 'bar' };
export default ({ name }) => {
const [state, setState] = useState(foo);
console.log("rendered!");
useEffect(() => {
setState(foo);
console.log("state reset!");
});
const handleClick = () => {
console.log("handleClick!");
setState(foo);
// setState({ ...foo, bar : 'baz' });
}
return (<div>
<h1>Hello {name}!</h1>
<button onClick={handleClick}>Click Me</button>
</div>);
};
You'll notice that even when the button is clicked since the value has not changed. it's not re-rendering the Component. If you change the argument that you call setState
with, it will re-render the component.
Here's a Code Sample for your ref.
Try commenting the first setState
and un-commenting the second one inside the handleClick
method to see the difference.
这篇关于使用钩子设置具有相同值的状态会导致重新渲染吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!