从React文档中,我了解到,只有在状态值发生变化时,组件才会重新渲染.
例如
import React, { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
console.log("I am rendering");
const handleButtonClick = () => {
setCount(0);
};
return (
<>
<button onClick={handleButtonClick}>Increment</button>
Count value is: {count}
</>
);
}
即使我们点击按钮,消息I am rendering
也只打印once,因为setCount
功能将值设置为0
,这是count
的当前值
由于当前值和future 值没有变化,因此该组件不会重新渲染.
意外行为
然而,当我们在setCount(0)
之前添加额外的行setCount(1)
时,没有观察到类似的行为
import React, { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
console.log("I am rendering");
const handleButtonClick = () => {
setCount(1); //this line has been added extra
setCount(0);
};
return (
<>
<button onClick={handleButtonClick}>Increment</button>
Count value is: {count}
</>
);
}
原则上,最终count
值的输出没有变化.但是,如果我们单击按钮,组件将重新呈现并打印消息I am rendering
我找不到这种行为的解释.这种行为符合预期吗?.
Shouldn't the component re-render only when the final value of the state is different from the current value ?