简体   繁体   English

如何更改 redux state 的嵌套 object 值

[英]How to change a nested object value of a redux state

I have the following state我有以下 state

const state = {
  courses: [],
  series: [],
  course: {
      title: 'testing',
      course_notes: [
    {
      id: 1,
      note: "one" // want to edit this
    },
    {
      id: 2,
      note: "two"
    }
  ]
}
}

I want to change state.course.course_notesp[0].name我想更改state.course.course_notesp[0].name

I've never fully understood how this works, read a lot of tutorials, I feel I know how it works but it always trips me up.我从来没有完全理解它是如何工作的,阅读了很多教程,我觉得我知道它是如何工作的,但它总是让我绊倒。 This is what I am trying这就是我正在尝试的

const m = {
  ...state, 
  course: {
    course_notes:[
      ...state.course.course_notes,
      state.course.course_notes.find(n => n.id === 1).note = "edited"
    ]
  }
}

That seems to add edited as an extra node.这似乎添加edited作为一个额外的节点。 state.course.course_notes.length ends up being 3 . state.course.course_notes.length最终为3

There are lots of ways you could modify the state of your store to update one element of course_notes.您可以通过多种方式修改商店的 state 以更新 course_notes 的一个元素。

If we assumed the ids to be unique, I would map the previous array modifying the element with id 1.如果我们假设 id 是唯一的,我会 map 前面的数组修改 id 为 1 的元素。

....
course_notes: state.course.course_notes.map(x => x === 1
  ? { ...x, note: 'edited' } 
  : x
)
...

You are using the spread operator for arrays like you would for objects.您正在对 arrays 使用扩展运算符,就像对对象一样。

Assume you have an object假设你有一个 object

const obj = { a: 1, b: 2 }

If you say:如果你说:

{...obj, a: 2}

What you are saying is:你说的是:

{ a: 1, b: 2, a: 2 }

The property a is defined twice, but the second one overrrides the first one.属性a被定义了两次,但第二个覆盖了第一个。

If you do something similar for an array, however, the result would be different:但是,如果您对数组执行类似的操作,结果会有所不同:

const arr = [1, 2];
const newArr = [...arr, arr[0]];

// here the result would be [1, 2, 1]

This is why when you are saying:这就是为什么当你说:

course_notes:[
  ...state.course.course_notes,
  state.course.course_notes.find(n => n.id === 1).note = "edited"
]

what it does is add an extra element to the array.它的作用是向数组添加一个额外的元素。

What you should do is instead create a modified version of the array, for example using map您应该做的是创建阵列的修改版本,例如使用map

course_notes: state.course.course_notes.map(el => {
    if (el.id === 1) {
        el.note = 'edited';
    }
    return el;
});

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

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