我想以不可变的方式更新状态对象,以便react和redux正常工作?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我想以不可变的方式更新状态对象,以便react和redux正常工作?相关的知识,希望对你有一定的参考价值。

我想以不可变的方式更新我的redux reducer状态中给定javascript对象中每个用户的firstName

我尝试了很多方法,但没有一种方法可行。

这是我的数据:

{"users":[{"key":1,"value":{"employeeID":1,"firstName":"Siddharth Kilam","mobileNumber":"+919987792049","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-09 09:15:05","lat":28.4453983,"lon":77.1012133,"eventTypeID":9,"employeeID":1},"attendanceRow":{"timestamp":"2019-04-09 09:05:39","lat":28.4453983,"lon":77.1012133,"eventTypeID":8,"employeeID":1},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"2019-04-11T04:34:00.000Z","endTime":"2019-04-11T12:34:00.000Z"}]},"offlinePeriod":3600000,"status":"Inactive"}},{"key":145,"value":{"employeeID":145,"firstName":"SidKilam2 Motorola","mobileNumber":"9599936991","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-03 12:20:16","lat":28.4455203,"lon":77.101336,"eventTypeID":9,"employeeID":145},"attendanceRow":{"timestamp":"2019-04-02 23:01:27","lat":28.4747009,"lon":77.0989274,"eventTypeID":9,"employeeID":145},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"1999-12-31T18:30:00.000Z","endTime":"2000-01-01T18:29:59.000Z"}]},"offlinePeriod":3600000,"status":"Offline"}}]};

My Current Reducer Function : 
 const newState = {
        ...state, // or state
        users: state.users.filter(user => {
          return user.value.status === online;
        })
      }

      return newState;
答案

使用map来做到这一点。

const newState = {
    ...state, // or state
    users: state.users.filter(user => {
      return user.value.status === online;
    }).map(user => {return {...user, value: {...user.value, firstName:"new name"}};});
  }

  return newState;
另一答案

您还需要传播用户对象以保持不变性,如下所示:

const newState = {
        ...state, 
        users: ([...state.users].filter(user => {
          return user.value.status === online;
        })).map(user => ({...user, value: {...user.value, firstName:"Vishal"}}));
      }

以上是关于我想以不可变的方式更新状态对象,以便react和redux正常工作?的主要内容,如果未能解决你的问题,请参考以下文章

react中的可变状态更新

javascript 更新状态React Redux不可变

从存储在 React 状态中的对象数组访问属性

react Immutability 理解

使用 React Native 获取时区

在 Immutable.js 中使用 React 的不可变助手