![](/img/trans.png)
[英]react better solution for custom hooks when using setInterval and stale closures
[英]Stale closures with react hooks and click events
我创建了一个代码框以便于调试:
https://codesandbox.io/s/hardcore-dirac-nh4iz?file=/src/App.tsx
我已经构建了一个我使用的 DataList 组件,例如:
function App() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
const handleSelect = () => {
setCount(count + 1);
countRef.current = count + 1;
console.log({ count });
};
return (
<>
<p>Stale closures prevent the count state from displaying correctly</p>
<DataList.List label="testing">
{data.map((d) => (
<DataList.Item key={d} onSelect={handleSelect}>
{d} {count}
</DataList.Item>
))}
</DataList.List>
</>
);
}
所有功能都在useListBox
钩子内部处理,其中包括从每个子节点获取onSelect
属性并将其绑定到 List 本身的单击事件。 但是,过时的闭包会阻止count
数值更新。
我将不胜感激任何帮助,因为陈旧的关闭还没有点击我。
我怀疑,我需要onSelect
依赖于handleClickEvent
回调,但不确定。
问题是您的useEffectOnMount
的定义方式。 每当您的children
更新时,即使在安装之后,您也需要考虑更改。 将其从useEffectOnMount
更改为useEffect
,一切都会奏效:-
分叉沙箱 - https://codesandbox.io/s/friendly-fog-inv8h?file=/src/components/DataList/DataList.tsx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.