繁体   English   中英

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

[英]Redux adding nested value to current state

我有以下状态:

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

我想为某个键提供一个新值,并用此替换当前状态。 但我也希望价值与前一个相结合。 例如,通过以下操作:

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

我会得到以下状态:

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

我怎样才能在reducer中做到这一点,以便案例保持不变? (使用...传播运算符,而不是ImmutableJS )。

编辑:

处理(应该)的减速器的一部分:

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

这就是我想要解决它的方式

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
  }

我希望它对你有所帮助。

您将需要使用spread运算符来传播旧值,然后传播newObject [key]值数组。

像这样的东西:

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
  }

编辑:我从lodash添加get实用程序函数,这样如果state.list[key] undefined ,它将返回一个空数组来传播而不是抛出错误。

暂无
暂无

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

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