简体   繁体   English

通过 Redux Reducer 中的键附加到数组访问

[英]Appending to an array access by a key in Redux Reducer

I'm trying to add to my state within a reducer.我正在尝试在减速器中添加到我的状态。 I need to access a key, and then add to an array within that key.我需要访问一个键,然后添加到该键内的数组。 This is what my state currently looks like:这是我目前的状态:

{teamMembers: {
    PersonId1: [{ object1 }, {object2 }]
    PersonId2: [{ object3 }, { object4 }]
    PersonId3: [{ object5 }, { object6 }]
}}

I need to access a PersonId , based on what the action inputs, and then append an item from the action to the array.我需要根据操作输入的内容访问PersonId ,然后将操作中的项目附加到数组中。 Ideally it would also create a new key and array if the key PersonId didn't already exist.理想情况下,如果密钥PersonId不存在,它还会创建一个新的密钥和数组。

In your reducer, just do a little data manipulation.在您的减速器中,只需进行一些数据操作。 Remember to only manipulate a copy of your state and not your actual state.请记住只操作您的状态的副本,而不是您的实际状态。

const action = {
  payload: {
    personId: 'PersonId4',
    item: {}
  }
}

const state = {
    PersonId1: [{ object1 }, {object2 }]
    PersonId2: [{ object3 }, { object4 }]
    PersonId3: [{ object5 }, { object6 }]
}
const {personId, item} = action.payload
let newState = {...state}
if (personId in newState) {
  newState[personId].push(item)
} else {
  newState[personId] = [item]
}
return newState

You can conditionally check for the existence of the key and then add it to an already existing array or create a new one.您可以有条件地检查键是否存在,然后将其添加到现有数组或创建一个新数组。

Something like this:像这样的东西:

const newItems = state[id] ? [...state[id], ...items] : items;
//...
return {
  ...state,
  [id]: newItems
}

Note that i'm using the object spread syntax which is a proposal (in stage 3 ) and you need the babel plugin babel-plugin-transform-object-rest-spread to support it (or babel stage 3 preset ).请注意,我正在使用对象传播语法,这是一个建议(在第 3 阶段),您需要 babel 插件babel-plugin-transform-object-rest-spread来支持它(或babel stage 3 preset )。

Running example:运行示例:

 const initialState = { teamMembers: { PersonId1: [{ name: 'object1' }, { name: 'object2' }], PersonId2: [{ name: 'object3' }, { name: 'object4' }], PersonId3: [{ name: 'object5' }, { name: 'object6' }] } }; const actionOne = { type: 'ADD', payload: { id: 'PersonId2', items: [{ name: 'object444' }] } } const actionTwo = { type: 'ADD', payload: { id: 'PersonId777', items: [{ name: 'object777' }] } } const reducer = (state = {}, action) => { switch (action.type) { case 'ADD': { const { id, items } = action.payload; const newItems = state[id] ? [...state[id], ...items] : items; return { ...state, [id]: newItems } } default: return state; } } const reducerResultOne = reducer(initialState.teamMembers, actionOne); console.log('reducerResultOne', reducerResultOne); const reducerResultTwo = reducer(initialState.teamMembers, actionTwo); console.log('reducerResultTwo', reducerResultTwo);

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

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