简体   繁体   English

Redux将嵌套值添加到当前状态

[英]Redux adding nested value to current state

I have the following state: 我有以下状态:

{
  list: {
    key1: {
      value: [{a: 'a'}, {b: 'b'}],
      fetching: true
    },
    key2: {
      value: [{c: 'c'}],
      fetching: true
    }
  }
}

I want to provide a new value for some key, and replace current state with this. 我想为某个键提供一个新值,并用此替换当前状态。 But I also want the value to be concated with the previous one. 但我也希望价值与前一个相结合。 So for example with the following action: 例如,通过以下操作:

key1: {
  value: [{d: 'd'}],
  fetching: false
}

I would get the following state: 我会得到以下状态:

{
  list: {
    key1: {
      value: [{a: 'a'}, {b: 'b'}, {d: 'd'}],
      fetching: false
    },
    key2: {
      value: [{c: 'c'}],
      fetching: true
    }
  }
}

How can I do that inside a reducer, so that the case remains immutable? 我怎样才能在reducer中做到这一点,以便案例保持不变? (using ... spread operator, not ImmutableJS ). (使用...传播运算符,而不是ImmutableJS )。

EDIT: 编辑:

Part of the reducer that handles (should to) that: 处理(应该)的减速器的一部分:

case "FOO_BAR":
  const key = action.payload.key;
  const newList = {...state.list};
  newList[key] = action.payload.newObject; // {value: ..., fetching: ...}
  return {
    ...state,
    list: newList
  }

It's how I'd like to solve it 这就是我想要解决它的方式

case "FOO_BAR":
  const oldList = {...state.list};
  const newKey1Value = action.payload.key.value;
  oldList.key1.value = oldList.key1.value.concat(newKey1Value);
  const newKey1fetching  = action.payload.key.fetching;
  oldList.key1.fetching =  newKey1fetching;
  return {
    ...state,
    list: oldList
  }

I hope it helps you. 我希望它对你有所帮助。

You will need to use the spread operator to spread the old values and then spread the newObject[key] value array. 您将需要使用spread运算符来传播旧值,然后传播newObject [key]值数组。

Something like this: 像这样的东西:

import { get } from 'lodash';

case "FOO_BAR":
  const { key, newObject } = action.payload;
  const newList = {
    ...state.list, 
    [key]: {
      value: [...get(state, 'list[key].value', []), ...newObject[key].value]
      fetching: newObject[key].fetching
    }
  };
  return {
    ...state,
    list: newList
  }

Edit: I added the get utility function from lodash so that if state.list[key] is undefined , it will return an empty array to spread rather than throwing an error. 编辑:我从lodash添加get实用程序函数,这样如果state.list[key] undefined ,它将返回一个空数组来传播而不是抛出错误。

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

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