[英]How to update item without recreating the whole list in React
Basically, from an API request, I have an array containing catalogs with a list of items which can be favorited.基本上,从 API 请求中,我有一个包含目录的数组,其中包含可以收藏的项目列表。 I display them using three main React components with hooks:
我使用三个带有钩子的主要 React 组件来展示它们:
Live
which makes the API request, stores the catalogs in state, and display one Catalog
at a time Live
发出 API 请求,将目录存储在 state 中,一次显示一个Catalog
Catalog
which receives items as a prop and a handleFavorite
function and displays a list of Item
Catalog
handleFavorite
并显示Item
列表Item
which receives an item as props and the handleFavorite
function and displays a like or dislike buttonItem
作为道具和handleFavorite
并显示一个喜欢或不喜欢按钮的项目Is there any way I can modify the favorited
property of a single item in the Catalog
component using hooks?有什么方法可以使用钩子修改
Catalog
组件中单个项目的favorited
属性? Otherwise, since the catalogues are stored in state in the Live
component, does that mean I have to recreate the whole array of catalogues every time I have to update one item in one catalog?否则,由于目录存储在
Live
组件中的 state 中,这是否意味着每次我必须更新一个目录中的一个项目时,我都必须重新创建整个目录数组?
There could be a few thousand items in all catalogs combined so it doesn't seem like a good way to handle that.所有目录中可能有几千个项目组合,所以这似乎不是处理这个问题的好方法。 I also thought about
useContext
but that doesn't seem to be what it's meant for.我也想过
useContext
但这似乎不是它的意思。
In Catalog
component you could use useMemo .在
Catalog
组件中,您可以使用useMemo 。 I quate from react official web site.我来自反应官方 web 网站。
useMemo will only recompute the memoized value when one of the dependencies has changed.
useMemo 只会在依赖项之一发生更改时重新计算记忆值。 This optimization helps to avoid expensive calculations on every render.
这种优化有助于避免在每次渲染时进行昂贵的计算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.