英文:
Component rerendering count is incorrect while using useRef in ReactJS
问题
我正在按照网上的教程学习useRef
Hook,大部分情况下都运行正常,只是在打印2后无法继续正常工作。请告诉我我在这里做错了什么。
在示例代码中,我想使用useRef
来计算组件的重新渲染次数。现在,如果您在输入框中输入一些内容,您会注意到它不会渲染出 2,但会打印出其他所有数字。
代码 -
const InputField = () => {
const [val, setVal] = useState("");
const comRef = useRef(1);
useEffect(() => {
comRef.current = comRef.current + 1;
});
return (
<div className="fieldset-input-textbox">
<input type="text" value={val} onChange={(e) => setVal(e.target.value)} />
<div className="">
This Component rendered {comRef.current}
{`${comRef.current > 1 ? " times" : " time"}`}.
</div>
</div>
);
};
export default InputField;
Code Sandbox链接 - https://codesandbox.io/s/busy-paper-f2qdhs?file=/src/InputField.js:54-542
英文:
I am following a tutorial from the web for learning useRef
Hook, which works mostly fine except it is unable to print 2 though after that it behaves normally. Let me know what I am doing wrong here.
In the example code, I want to count the re-render of a component using useRef
. Now if you type something in the input box you will notice it won't render 2 rest all numbers it will print.
Code -
const InputField = () => {
const [val, setVal] = useState("");
const comRef = useRef(1);
useEffect(() => {
comRef.current = comRef.current + 1;
});
return (
<div className="fieldset-input-textbox">
<input type="text" value={val} onChange={(e) => setVal(e.target.value)} />
<div className="">
This Component rendered {comRef.current}
{`${comRef.current > 1 ? " times" : " time"}`}.
</div>
</div>
);
};
export default InputField;
Code Sandbox Link - https://codesandbox.io/s/busy-paper-f2qdhs?file=/src/InputField.js:54-542
答案1
得分: 0
你的根组件被包裹在 <React.StrictMode>
中,因此在开发过程中,React 会在初始挂载时将组件渲染两次,以帮助捕捉意外的不纯情况。
这会导致效果运行两次,因此在组件挂载后,comRef.current
变为 3
。更改引用不会引发重新渲染,因此此新值在在文本字段中输入后才显示,这会更新 val
状态。然后,它将显示 3
,接下来的效果将在此之后运行。
英文:
You have your root component wrapped in <React.StrictMode>
, so during development, React will render the component twice for the initial mount to help catch accidental impurities.
This causes the effect to be run twice, so comRef.current
becomes 3
after the component is mounted. Changing refs does not cause rerenders, so this new value is not shown until typing in the text field, which updates the val
state. Then, it will display 3
and the next effect will run after that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论