在React函数组件中使用setInterval无法获取更新后的props。

huangapple go评论51阅读模式
英文:

Unable to get updated props in setInterval React functional component

问题

对于在 setInterval 内部无法获取更新后的属性值的问题,第一个代码示例无法直接访问更新后的 counter 值。即使 counter 的值在浏览器中每秒更新,setInterval 内部的 console.log(counter) 仍然会保持初始值而非更新后的值。

第二个解决方案使用了 useRef 来在 Component1 中存储 counter 的引用,以便在 setInterval 内部访问最新值。尽管这种方法有效,但是需要额外的内存空间。

目前没有直接的解决方案可以避免使用额外的内存空间,因为 JavaScript 的闭包特性导致 setInterval 内部无法直接获取更新后的值。这意味着类似 useRef 或其他方法是目前可以使用的最佳选择,尽管它们可能需要额外的内存。

希望将来的 React 版本或 JavaScript 规范可能会提供更简洁的解决方案来处理这种情况,但到目前为止,使用引用或其他技巧似乎是目前可行的最佳方式。

英文:

I am unable to get the updated prop in setInterval inside Component1, it gives me the old value

following is the code I am using:

import { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const 
0
+
网站访问量
= useState(0); useEffect(() => { const intervalID = setInterval(() => { setCounter((counter) => counter + 1); }, 1000); return () => { clearInterval(intervalID); }; }, []); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <Component1 counter={counter} /> </div> ); } const Component1 = ({ counter }) => { useEffect(() => { const intervalID = setInterval(() => { console.log(counter); }, 1000); return () => { clearInterval(intervalID); }; }, []); return <h1>Component1 count: {counter}</h1>; };

In this code inside Component1, the counter's value is updated after every second on the browser, but on the console.log inside setInterval, I am always getting the initial value not the updated one.

I also get a solution which looks like this

import { useState, useEffect, useRef } from "react";
import "./styles.css";

export default function App() {
  const 
0
+
网站访问量
= useState(0); useEffect(() => { const intervalID = setInterval(() => { setCounter((counter) => counter + 1); }, 1000); return () => { clearInterval(intervalID); }; }, []); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <Component1 counter={counter} /> </div> ); } const Component1 = ({ counter }) => { const counterRef = useRef(null); counterRef.current = counter; useEffect(() => { const intervalID = setInterval(() => { console.log(counterRef.current); }, 1000); return () => { clearInterval(intervalID); }; }, []); return <h1>Component1 count: {counter}</h1>; };

But in this solution, I have to use extra memory space as I am creating a ref and assigning value to it.

Is there any better solution there to get updated value inside setInterval to this the correct way to do it.

答案1

得分: 1

以下是已翻译的内容:

在面对 JavaScript 的闭包行为时,您可以尝试在这种情况下使用以下代码:

useEffect(() => {
  const intervalId = setInterval(() => {
    console.log('count is', counter);
  }, 1000);

  return () => clearInterval(intervalId);
}, [counter]);

但在您的情况下,以下代码更适用于 Component1:

useEffect(() => {
  console.log(counter);
}, [counter]);
英文:

You can try this one in scenario, where you face closure behavior of JavaScript,

    useEffect(() => {
    const intervalId = setInterval(() => {
      console.log('count is', counter);
    }, 1000);

    return () => clearInterval(intervalId);
  }, 
0
+
网站访问量
);

But in your scenario this will be more suitable in Component1,

useEffect(() => {
    console.log(counter);
  }, 
0
+
网站访问量
);

huangapple
  • 本文由 发表于 2023年2月14日 19:51:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447435.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定