代码之家  ›  专栏  ›  技术社区  ›  I_A

按索引重复读取数组元素

  •  0
  • I_A  · 技术社区  · 4 年前

    我有一个存储在redux中的post对象数组。我正在映射Post,并将ID和index传递给Post组件:

    posts.map((post, index) => {
      <Post id={post.id} index={index} />
    });
    

    redux style guide 州:

    更喜欢在Redux存储中订阅更多的UI组件,并以更细粒度的级别读取数据。。。

    <UserList> 组件和读取整个用户数组 < 检索所有用户标识的列表,将列表项呈现为 <UserListItem userId={userId}> <UserListItem>

    但是,我没有postID列表,但是我仍然试图通过映射post并传递对post组件的引用(而不是post本身)来订阅更多的组件。(这是个好主意吗?)

    我的问题是关于我应该如何阅读商店的帖子。无论是按ID还是按索引:

    1. 岗位=state.posts.find(岗位=>邮政编码=== 道具id)
    2. 岗位=国家邮政局[道具索引]

    显然,按索引阅读会快得多。但是posts数组可以重新排序。所以我想知道map函数创建的索引是否可靠?

    0 回复  |  直到 4 年前
        1
  •  1
  •   Julien Deniau    4 年前

    这里唯一的“问题”是,随着时间的推移,您的应用程序可能会变得越来越复杂,以后很难对其进行维护。

    find 方法很好,如果您的商店中没有数百个商品,则不会有问题。

      function reducer(action, state) {
        switch (action.type) {
          case 'YOUR_CASE': {
            return {
              ...state,
    -         itemList: action.itemList,
    +         itemList: Object.fromEntries(
    +           action.itemList.map(item => ([item.id, item]))
    +         ),
            }
          }
        }
      } 
    

    你的商店里就会有这样一个物品:

    {
      1: {
        id: 1,
        title: 'some item',
      },
      2: {
        id: 2,
        title: 'some other item',
      },
    }
    

    小心点 Object.fromEntries 只是一个 recent API ,您可能需要填充它。

    itemList 作为之前的数组:

    - itemList: state.itemList,
    + itemList: Object.values(state.itemList),