我正在按照网络上的一个教程来学习useRef
钩子,它基本上工作得很好,除了它不能打印2,尽管之后它的行为正常.让我知道我到底做错了什么.
在示例代码中,我希望使用useRef
计算组件的重新呈现次数.现在,如果您在输入框中输入一些内容,您会注意到它不会呈现2个REST,所有它将打印的数字.
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;
代码Sandbox LINK-https://codesandbox.io/s/busy-paper-f2qdhs?file=/src/InputField.js:54-542