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

问题描述 投票:0回答:2

我想以不可变的方式更新我的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;
javascript reactjs redux immutability
2个回答
0
投票

使用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;

0
投票

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

const newState = {
        ...state, 
        users: ([...state.users].filter(user => {
          return user.value.status === online;
        })).map(user => ({...user, value: {...user.value, firstName:"Vishal"}}));
      }
© www.soinside.com 2019 - 2024. All rights reserved.