繁体   English   中英

如何更改 redux state 的嵌套 object 值

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

我有以下 state

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

我想更改state.course.course_notesp[0].name

我从来没有完全理解它是如何工作的,阅读了很多教程,我觉得我知道它是如何工作的,但它总是让我绊倒。 这就是我正在尝试的

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

这似乎添加edited作为一个额外的节点。 state.course.course_notes.length最终为3

您可以通过多种方式修改商店的 state 以更新 course_notes 的一个元素。

如果我们假设 id 是唯一的,我会 map 前面的数组修改 id 为 1 的元素。

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

您正在对 arrays 使用扩展运算符,就像对对象一样。

假设你有一个 object

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

如果你说:

{...obj, a: 2}

你说的是:

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

属性a被定义了两次,但第二个覆盖了第一个。

但是,如果您对数组执行类似的操作,结果会有所不同:

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

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

这就是为什么当你说:

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

它的作用是向数组添加一个额外的元素。

您应该做的是创建阵列的修改版本,例如使用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