简体   繁体   English

如何在 Redux Store 中按 id 存储项目

[英]How can I store items by id in Redux Store

I am using Redux in my React application.我在我的 React 应用程序中使用 Redux。 However items are always stored by index , like that =>但是,项目始终按index存储,就像那样 =>

店铺

I want to store them by ids , like instead of 0 first item's index should be 41 .我想通过ids存储它们,比如第一个项目的索引应该是41而不是0 How can I do that?我怎样才能做到这一点?

reducer.js减速器.js

export function ratedPosts(state=[], action) {
    enableES5()
    return (
        produce(state, draft => {
            const rate = action.Rate
            switch (action.type) {
                case RATE_POST:
                    draft.unshift({postId: action.postId, rate: rate})
                    break
                case RATE_POST_UPDATE:
                    draft.map(post => post.postId === action.postId).rate = rate
                    break
                default:
                    return draft
            }
        })
    )
}

You can't do that with arrays, but you can do that with objects.你不能用数组做到这一点,但你可以用对象做到这一点。 I see also that you are using Array.unshift to add new posts, keep in mind that arrays do not guarantee the sequence of the items, even though it works most of the time.我还看到您正在使用 Array.unshift 添加新帖子,请记住,即使数组在大多数情况下都有效,也不能保证项目的顺序。

You'll need to convert your data structure to use objects instead of array, but in the getter function you could convert to an array so it can be more easily used in the frontend.您需要将数据结构转换为使用对象而不是数组,但在 getter 函数中,您可以转换为数组,以便在前端更容易使用。

You can set an object ID programmatically using [ ]您可以使用[ ]编程方式设置对象 ID

let myObject = {}
const idOne = 'abc'
const idTwo = 'def'

draft[idOne] = "Hello"  // draft.abc === "Hello"
draft[idTwo] = "World"  // draft.def === "World"

draft === {
  abc: "Hello",
  def: "World"
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM