简体   繁体   中英

Unshift data to array in Redux reducer

On the dispatch of the UPDATE_DATA action, I am able to push data to my state.data array in the reducer with the following code.

const toPush = {
    name : "Pushed Name",
    id_name : 100,
    more1 : "pushedMore01"
}

case "UPDATE_DATA":
  return {
    ...state,
    data: [...state.data, toPush],
    isFetching: false
}

How do I unshift rather than push the data to state? What would be clean ES6 syntax for the same?

Just switch the order:

data: [toPush, ...state.data]

This will insert the new item at the beginning, then spread the rest of the previous data after it.

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