[英]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.