代码之家  ›  专栏  ›  技术社区  ›  catandmouse

如何在redux中正确地更新数组中的项而不发生变异?

  •  0
  • catandmouse  · 技术社区  · 7 年前
    const state = [
        {
            list: []
        }
    ];
    

    列表是学生对象的列表,例如:

    list: [
       { id: 1, name: "Mark", attendance: true },
       { id: 2, name: "John", attendance: false }
    ]
    

    我有一个按钮,可以触发对API的post请求,将出勤率更改为true。Post请求返回已更改的student对象,例如:

    { id: 2, name: "John", attendance: true }
    

    这工作正常,如果没有错误,将调度 ATTENDANCE_SUCCESS .

    现在,在这种设置下:

    export function students(state, action) {
        let latestState = state[state.length - 1],
            newState = Object.assign({}, latestState);
        switch (action.type) {
           case "ATTENDANCE_SUCCESS":
              if (action.res.errorCode == 0) {
                 // Need to change redux state 'attendance' value to true for a student with ID returned from the POST request
              }
        }
    

    const studentChanged = newState.list.find(function(student) {
      return (
            student.id ===
            action.res.data.id
      );
    });
    studentChanged.attendance = true;
    

    但是它改变了redux商店中的状态(尽管我不确定它到底是如何发生的,因为我假设newState已经是一个副本)。

    正确的方法是什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Alexander Staroselsky    7 年前

    id 项的名称与 attendance 财产。 Array.prototype.map 返回一个新数组,使其不可变。

    export function students(state, action) {
      switch (action.type) {
        case "ATTENDANCE_SUCCESS":
          if (action.res.errorCode == 0) {
            return state.map(student => {
              // we want to leave non matching items unaltered
              if (student.id !== action.res.data.id) {
                return student;
              }
    
              return { ...student, attendance: true };
            });
          }
    
          return state;          
        default:
          return state;
      }
    }
    

    这是一个 StackBlitz 演示功能。

    希望这有帮助!