简体   繁体   English

如何在不重新创建 React 中的整个列表的情况下更新项目

[英]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 button接收一个Item作为道具和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.这种优化有助于避免在每次渲染时进行昂贵的计算。

Read more about useMemo here .在此处阅读有关 useMemo 的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React:更新列表中的一个项目而不重新创建所有项目 - React: update one item in a list without recreating all items 如何在不更改整个列表的情况下编辑列表中的项目? - How can I edit an item in a list without changing the whole list? 如何避免重新呈现整个List而不是将新项添加到react JS中的DOM列表? - How to avoid re-rendering the whole List instead of adding the new item to the DOM list in react JS? 如何只更新一些行项目而不在 NetSuite 上保存整条记录? - How to just update some line item without saving a whole record on NetSuite? 如何使用 React Context 更新列表中的单个项目? - How do I update a single item in list with React Context? 使用reactjs,在不更新整个列表的情况下更新列表中的项目? - Using reactjs, updating an item in a list without updating the whole list? 如何在不使用 id 的情况下删除 React 功能组件中的列表项 - How to delete a list item in React Functional Component without using id 如何模糊除列表项之外的整个身体? - How to blur the whole body except a list item? React-Native 整个列表删除而不是选中项 - React-Native whole list deleting instead of selected item 如何在不刷新整个页面的情况下更新树? - How to update a tree without refreshing whole page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM