在我的反应记事本中创建了一个缓存方法,并遇到了一个小错误,我使用 useEffect 设置 3 秒的间隔,然后如果标题和描述不为 false,则更新缓存持有者,尽管当它开始运行时并且标题或描述更改回 false(空或无效值)间隔无法识别更新
当它开始运行时,即使标题或描述已清空,它也不会停止,这必须将间隔条件设置为 false
let [heading, setHeading] = useState(addTextCache.heading)
let [description, setDescription] = useState(addTextCache.description)
useEffect(() => {
let count = 0
setInterval(() => {
if(heading != false && description != false) {
count++
console.log(count)
console.log(heading != false && description != false)
setAddTextCache({
heading: heading,
description: description
})
}
}, 3000)
}, [heading, description])
useEffect
钩子回调对间隔实例化时的heading
和description
状态值有一个闭包,因此回调永远看不到任何更新的值。useEffect
钩子永远不会清理现有间隔。使用 React ref 缓存
heading
和 description
状态值,可以在间隔回调中访问这些值。
const [heading, setHeading] = useState(addTextCache.heading);
const [description, setDescription] = useState(addTextCache.description);
// React refs and useEffect hooks to cache current state values
const headingRef = useRef(heading);
const descriptionRef = useRef(description);
useEffect(() => {
headingRef.current = heading;
}, [heading]);
useEffect(() => {
descriptionRef.current = description;
}, [description]);
// Instantiate the interval once on component mount
useEffect(() => {
const intervalRef = setInterval(() => {
const heading = headingRef.current;
const descriptionRef = descriptionRef.current;
if (heading != false && description != false) {
setAddTextCache({ heading, description });
// clear interval once heading and description are truthy
clearInterval(intervalRef);
}
}, 3000);
// Return cleanup function to clear interval on component unmount
return () => {
clearInterval(intervalRef);
};
}, []);