简体   繁体   中英

How can I store items by id in Redux Store

I am using Redux in my React application. However items are always stored by index , like that =>

店铺

I want to store them by ids , like instead of 0 first item's index should be 41 . How can I do that?

reducer.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.

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.

You can set an object ID programmatically using [ ]

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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