我可以在React / Redux应用程序

时间:2017-08-07 17:34:45

标签: reactjs redux immutable.js

在提交带有一些更新值的表单时,我需要更新状态以反映这些更改,但我是Immutable.js的新手并且不确定如何执行此操作。

是否可以将函数作为第二个参数传递以设置或更新以根据特定条件更新值。

我有一个接收状态的函数和一个名为values的对象数组。值中的数据如下所示:

[
  {
    key: 'name',
    value: 'fred'
  },
  {
    key: 'height',
    value: '201'
  },
  {
    key: 'weight',
    value: '78'
  }
]

我需要映射这些数据和状态列表,并使用values数组更新状态列表中的相应值。

我该怎么做?我已经整理了一个函数,Reducer调用该函数来更新新数据的状态,但不确定如何获得最终结果

 function updateValue(state, values = []) { 
  const items = state.get('items').map((i) => {
    const key = i.get('key');

    values.map(v => {
      if (v.key === key) {
        return state.update('value', v.value);
      }
    })
  });

  return state.update('items', /* Can I use a function here to replace the code above.. to update all of the items in the state List that correspond to the items in the measurements array (which have new values) */);
}

非常感谢。

更新 尝试以下操作,但收到错误:Expected [K, V] tuple: i

function updateValue(state, values = []) { 
  const items = state.get('items').map((i) => {
    const key = i.get('key');

    values.map(v => {
      if (v.key === key) {
        return state.update('value', v.value);
      }
    })
  });

  return state.update('items', items);
}

有关Immutable错误的更多细节:

function validateEntry(entry) {
    if (entry !== Object(entry)) {
      throw new TypeError('Expected [K, V] tuple: ' + entry);
    }
  }

1 个答案:

答案 0 :(得分:0)

您可以使用'合并'返回新对象:

return state.merge({         项目:价值观,       });