更新数组生命周期内对象的值

时间:2018-05-26 02:32:25

标签: javascript arrays reactjs object

我试图通过一系列进程来控制数组的值。这用于调试,但也帮助我看到javascript方法如何改变引用类型,如数组和对象。

在这种情况下,我记录的数组中的对象值也在数组的对象中:

样本模型:

{key: '1234', class: 'Math 10', fname: 'john', lname: 'doe',
    homework: [
      {key: '123', check: 'yes'},
      {key: '12356', check: 'no'},
      {key: '12356789', check: 'na'},
    ]
    },

我想改变的是每个家庭作业中“检查”的价值。

问题/困惑

当我在编写代码时控制台记录家庭作业对象以监控“检查”的值时,当我更改“检查”的值时,所有以前的控制台日志都会显示此新值。

当我在确切的时间点设置值时,这怎么可能?我认为它与引用类型有关,但我使用切片方法来确保我复制数组。

    const value = event.target.getAttribute("data-value");
    console.log("data-value is = ", value);

    const studentKey = event.target.getAttribute("data-studentkey");
    console.log("student key is = ", studentKey);

    const selectedHomeworkKey = this.state.selectedHomework;
    console.log("Seleted Homework Key is ", selectedHomeworkKey);

    const students = this.state.students.slice();
    console.log("state says students are", students);

    const selectedStudents = students.filter((student)=>{
      return( student.key === studentKey);
    })
    console.log("After filter, students is ", selectedStudents);

    const nonSelectedStudents = students.filter((student)=>{
      return( student.key !== studentKey);
    })
    console.log("Non selected students are ", nonSelectedStudents);

    const homeworkArray = selectedStudents[0].homework.slice();
    console.log("homework of the selected student is ", homeworkArray);

    const selectedHomework = homeworkArray.filter((homework) => {
      return (homework.key === selectedHomeworkKey);
    })
    console.log("selected homework for selected student is ", selectedHomework);

    let updatedHomework = selectedHomework.slice();
    console.log("updated homework before update is", updatedHomework)

    updatedHomework[0].check = value;
    console.log("updated homework after update is", updatedHomework)

enter image description here

问题

为什么在所有以前的console.logs中都显示check'yes'的值,即使它只应该在最后一个console.log中显示这个值?

1 个答案:

答案 0 :(得分:0)

只要您使用React,就应该避免改变状态。这正是您在代码中所做的事情。如果this.state.students是一个对象数组.slice()将不会产生任何影响(当您尝试更改某个对象的属性时,您将从另一个数组中切出一个属性,该属性将是在源数组中也发生了变化)

你可能想要一些不变的助手来更容易地改变你的状态。我使用https://github.com/kolodny/immutability-helper

如果需要,您可以尝试深层克隆整个对象。看看https://lodash.com/docs/4.17.10#cloneDeep

作为一种解决方法,您还可以使用JSON.parse(JSON.stringify(object));快速克隆对象。