简体   繁体   English

useRef 有时未定义,即使值存在

[英]useRef is sometimes undefined even tho value exists

I'm trying to keep a previous value that is constantly updated through my store using the useRef hook as below, however, the ref value is sometimes undefined even tho I am only setting it when the value exists.我正在尝试使用 useRef 挂钩保留一个以前的值,该值通过我的商店不断更新,如下所示,但是,ref 值有时是未定义的,即使我只在该值存在时设置它。

const price = useSelector(getPrice(props.index));
let prevPriceRef = useRef();

useEffect(() => {
        if(price) {
            prevPriceRef.current = price;
        }
    }, [ price ])

console.log(prevPriceRef.current) sometimes returns undefined, who is it possible? console.log(prevPriceRef.current) 有时会返回undefined,这是谁可能的?

在此处输入图像描述

Create a separate hook to handle/record previous value创建一个单独的钩子来处理/记录以前的值

function usePrevious(value) {

  const ref = useRef();
  
  useEffect(() => {
    ref.current = value;
  }, [value]); 

  return ref.current;
}

Use it by calling通过调用使用它

const prevPrice = usePrevious(price);

One thing to note, you are checking for if (price) {} which will not execute if your price is 0 => Zero and will return undefined as you will not be setting the current value to the ref.需要注意的一件事是,您正在检查if (price) {}如果您的价格为0 => 零,它将不会执行并将返回 undefined 因为您不会将当前值设置为 ref。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Discord.js V13 player.getQueue() 即使存在队列也返回未定义 - Discord.js V13 player.getQueue() returns undefined even tho a queue exists 即使值存在,属性也会返回未定义…? - Property returns undefined even though the value exists…? JS Class 属性“未定义”,即使它看起来已定义 - JS Class property "is undefined" even tho it appears to be defined 即使值存在,为什么对象键返回 undefined - Why object key returns undefined even though value exists 如何过滤有时未定义的值? - How to filter for a value that is sometimes undefined? React - State 保持相同的值,即使它已更新。 (内部函数) - React - State keeps same value even tho it is updated. (Inside function) 我在firebug中收到一个未定义的错误,即使我可以看到该值存在! - I get an undefined error in firebug , even if I can see the value exists!…why? HTML input[type=range] 不会改变外观,即使它接收到值变化 - HTML input[type=range] does not change appearance even tho it receives value-change 即使在 useEffect 中也没有设置 React useRef - React useRef is not setting even in useEffect 即使之前调用了该行,也不会执行操作 - Actions is not performed even tho the line is called earlier
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM