Javascript 使用react钩子和click事件过时闭包

Javascript 使用react钩子和click事件过时闭包,javascript,reactjs,types,react-hooks,closures,Javascript,Reactjs,Types,React Hooks,Closures,我创建了一个codesandbox以便于调试: 我已经构建了一个DataList组件,我使用它如下: function App() { const [count, setCount] = useState(0); const countRef = useRef(count); const handleSelect = () => { setCount(count + 1); countRef.current = count + 1; console.

我创建了一个codesandbox以便于调试:

我已经构建了一个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>
    </>
  );
}
函数应用程序(){
const[count,setCount]=useState(0);
const countRef=useRef(计数);
const handleSelect=()=>{
设置计数(计数+1);
countRef.current=计数+1;
log({count});
};
返回(
陈旧的闭包会阻止计数状态正确显示

{data.map((d)=>( {d} {count} ))} ); }
所有功能都在
useListBox
钩子中处理,其中包括从每个子级获取
onSelect
道具,并将其绑定到列表本身上的单击事件。但是,过时的闭包会阻止
计数
值的更新

我将感谢任何帮助,因为陈旧的闭包还没有点击我


我怀疑,我需要
onSelect
依赖于
handleClickEvent
回调,但不确定。

问题在于
useffectonmount
的定义方式。当您的
子项更新时,即使在装载之后,您也需要考虑更改。将其从
useffectonmount
更改为
useffecton
,事情就会正常进行:-


叉形沙箱-

我感觉自己很愚蠢,但又因为这么简单而受到鼓励。感谢您抽出时间帮忙:)