goo*_*els 2 state filtering reactjs use-reducer use-state
我正在建立该国餐馆的目录。该 API 返回一组对象,每个对象都包含诸如restaurantName、restaurantLocation、restaurantPriceRange 等字段。
我想创建一个过滤组件,它将餐厅数组减少到仅包含那些符合搜索条件的餐厅的子集。我还需要通过 URL 传递过滤器值,为此我认为应该使用路由器。
我正在考虑使用 useState 挂钩存储初始数据集,然后使用 useReducer 存储活动过滤器选择和过滤后的餐厅集合的子集,仅包含那些与搜索条件匹配的餐厅集合,但我觉得这是一个笨拙的解决方案,因为我有效将复制整个餐厅集合的一个子集。
但是,如果我不使用 useState 将初始数据集存储在单独的对象中,则一旦应用过滤器,所有不匹配的内容都将永远消失。
实现这一目标的最佳方法是什么?
免责声明:我知道如何在 JavaScript 中过滤数组,并且完全了解过滤器、映射、排序等功能。这个问题是关于 React 生态系统的,以及在反应应用程序。我知道当我为其编写代码时,我仍然需要在我的减速器中使用 Array.prototype.filter 。
你在征求意见,所以这是我的。React 状态(无论是 \xe2\x80\x99suseState还是useReducer)仅应用于有状态值 \xe2\x80\x94,这些值会发生变化并导致渲染数据发生变化。过滤后的餐馆列表不是一个有状态的值。过滤器是一个有状态的值,过滤后的列表源自该状态。过滤后的列表应该是您在每次渲染时生成的常量。如果组件中有其他状态或属性发生变化,但不会影响过滤列表,则可以使用钩子useMemo来记忆过滤列表,以防止不必要的重新计算。
伪代码
\nimport React, {useMemo} from \xe2\x80\x9creact\xe2\x80\x9d;\nimport {useLocation} from \xe2\x80\x9creact-router-dom\xe2\x80\x9d;\n\nexport const MyComponent = ({restaurants}) => {\n\n const location = useLocation();\n\n const filteredRestaurants = useMemo( () => {\n return restaurants.filter( /* some code */ );\n }, [location, restaurants] ); //dependency on location and restaurants \n\n return (\n <Wrapper>\n <EditFiltersComponent />\n <List>\n {filteredRestaurants.map( restaurant => \n <Restaurant {...restaurant} />\n )}\n </List>\n </Wrapper>\n )\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
6637 次 |
| 最近记录: |