[英]React useRef current not updating every time
I have a component that uses the useRef
hook on a div in order to calculate the height whenever a component is removed from that div.我有一个组件,它在 div 上使用
useRef
挂钩,以便在从该 div 中删除组件时计算高度。
The problem I am having is that the clientHeight
is not always updating when I remove an element from the div.我遇到的问题是,当我从 div 中删除一个元素时,
clientHeight
并不总是更新。 It does work if I use useState
and a useEffect
.如果我使用
useState
和useEffect
,它确实有效。 Is there any reason why the following method won't work?以下方法不起作用有什么原因吗? How can I get this to work without using more state and another useEffect?
如何在不使用更多 state 和另一个 useEffect 的情况下使其工作?
Doesnt work:不起作用:
useEffect(() => {
dispatch(setAppNotificationHeight(notificationRef.current?.clientHeight));
}, [notificationRef.current?.clientHeight]);
Works:作品:
const [height, setHeight] = useState<number | undefined>(undefined);
useEffect(() => {
setHeight(notificationRef.current?.clientHeight);
});
useEffect(() => {
dispatch(setAppNotificationHeight(height));
}, [height]);
I think your issue is discussed in here .我认为您的问题已在此处讨论。 Mutating a reference does not necessarily trigger a rerender, and does not necessarily trigger the useEffect.
改变引用不一定会触发重新渲染,也不一定会触发 useEffect。 You could use a useCallback hook instead of your working solution (see code snippet from this answer in particular).
您可以使用 useCallback 挂钩而不是您的工作解决方案(特别是参见此答案中的代码片段)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.