如何克隆道具并更改特定数据

时间:2017-11-08 23:42:00

标签: reactjs redux

如何在发送到redux状态之前编辑道具?基本上你不能改变你的状态所以我必须分配一个全新的数据。

const graphQLReturnedData = [

  { id: 1, foo: "bar", <longer-list> },
  { id: 2, foo: "pub", <longer-list> },

]


graphQLReturnedData.find(t => t.id === 1  ).foo = "me"; // Cannot assign to read only property...

确切的问题是,如何克隆道具并更改对象值?

没有运气
var newData = Object.assign({}, graphQLReturnedData)
newData.find(t => t.id === 1  ).foo = "phew";

当我只需要更改一个小值时,Redux需要一个全新的数据。

1 个答案:

答案 0 :(得分:1)

您的header, nav, main, footer { display: block; } * { box-sizing: border-box; } body { background-color: #3f2860; color: #3f2860; font-family: Veranda, Arial, sans-serif; } header { background-color: #9bc1c2; background-image: url(lilyheader.jpg); background-position: right; background-repeat: no-repeat; height: 150px; } h1 { padding-top: 50px; padding-left: 2em; } nav { font-weight: bold; float: left; width: 160px; padding: 1em; } nav a { text-decoration: none; font-weight: bold; padding: 1em; display: block; text-align: center; border: 3px outset #CCCCCC; margin-botton: 1em;} nav a:link { color: #497777; } nav a:visited { color: #497777; } nav a:hover { color: #A26100; border: 3px inset #333333; } nav ul { list-style-type: none; padding-left: 0; } main { padding-right: 2em; margin-left: 170px; padding-top: 1em; display: block; } /*This was missing -->*/ .floatleft { float: left; margin-right: 4em; } .studio { font-style: italic; } .company{ font-style: italic; } footer { background-color: #9bc1c2; font-size: .60em; font-style: italic; text-align: center; padding: 1em; } clear { clear: both; } #wrapper { background-color: #f5f5f5; min-width: 1200px; max-width: 1480px; width: 80%; margin-right: auto; margin-left: auto; }克隆数组对象,但其中的元素仍然是具有只读属性的相同对象。如果您使用Object.assign,则可以返回一个新数组,其中包含相应map的新对象(假设id在数组中是唯一的):

id

或使用const newData = graphQLReturnedData.map(t => t.id !== 1 ? t : {...t, foo: "me"});

Object.assign