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)
你必须记住每个函数
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)
| 归档时间: |
|
| 查看次数: |
196 次 |
| 最近记录: |