如何在 React 中使用 useCallback 和柯里化函数?

Epp*_*ple 5 javascript reactjs

我用来useCallback记录我的回调函数,但它似乎不适用于柯里化函数,尽管我将 PhotoItem 包装在 React.memo() 中,但我的组件在重新渲染PhotoItem时总是重新渲染。MyListPhoto因为handleDeletefunction 是柯里化函数,所以有什么方法可以与 useCallback 一起使用吗?

const MyListPhoto = () => {
   ...other state...
   const { delete } = useDeletePhoto();

   // always create new function when component re-render
   const handleDelete = useCallback((index) => (photoId) => {
      delete(photoId, index)
   }, []);

   return (
     <ul>
        {photos.map((photo, index) => (
           <PhotoItem
              key={photo.id}
              photo={photo}
              onDelete={handleDelete(index)}
           />
        ))}
     </ul>
   )
}
Run Code Online (Sandbox Code Playgroud)

照片项目组件:

const PhotoItem = React.memo(({ photo, onDelete }) => {
    console.log('re-render');

    return (
      ...
    )
})
Run Code Online (Sandbox Code Playgroud)

Kon*_*owy 5

你必须记住每个函数

const MyListPhoto = () => {
  // ...other state...
  const { del } = useDeletePhoto();

  const deleteHandlers = useMemo(() => {
    return photos.map((photo, index) => (photoId) => del(photoId, index));
  }, [photos]);

  return (
    <ul>
      {photos.map((photo, index) => (
        <PhotoItem
          key={photo.id}
          photo={photo}
          onDelete={deleteHandlers[index]}
        />
      ))}
    </ul>
  );
};
Run Code Online (Sandbox Code Playgroud)

  • 因为 `useCallback` 返回一个函数,但您想要与 `photos.length` 一样多的函数 (3认同)