英文:
How to use useCallback with currying function in React?
问题
我正在使用useCallback
来记忆我的回调函数,但似乎在柯里化函数中不起作用,我的PhotoItem
组件在MyListPhoto
重新渲染时总是重新渲染,尽管我在PhotoItem
中包装了React.memo()。因为handleDelete
函数是柯里化函数,是否有办法在useCallback
中使用它?
const MyListPhoto = () => {
...其他状态...
const { delete } = useDeletePhoto();
// 每次组件重新渲染时都会创建新函数
const handleDelete = useCallback((index) => (photoId) => {
delete(photoId, index)
}, []);
return (
<ul>
{photos.map((photo, index) => (
<PhotoItem
key={photo.id}
photo={photo}
onDelete={handleDelete(index)}
/>
))}
</ul>
)
}
// PhotoItem 组件:
const PhotoItem = React.memo(({ photo, onDelete }) => {
console.log('重新渲染');
return (
...
)
})
英文:
I am using useCallback
to memo my callback function but it doesn't seem to work with currying function, my PhotoItem
component always re-render when MyListPhoto
re-render although I wrapping my PhotoItem in React.memo(). Because handleDelete
function is a currying function, is there any way to use with 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>
)
}
PhotoItem component:
const PhotoItem = React.memo(({ photo, onDelete }) => {
console.log('re-render');
return (
...
)
})
答案1
得分: 4
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>
);
};
英文:
You have to memoize each function
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>
);
};
答案2
得分: -1
抱歉,我没有理解重点!为什么你需要记住这个函数?
这样怎么样:
...
return <ul>
{photos.map((photo, index) => (
<PhotoItem key={photo.id} photo={photo} onDelete={() => delete(photo.id, index)} />
</ul>
)
英文:
Sorry, I didn't get the point! Why do you need to memorize the function?
how about this:
...
return <ul>
{photos.map((photo, index) => (
<PhotoItem key={photo.id} photo={photo} onDelete={() => delete(photo.id, index)} />
</ul>
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论