简体   繁体   中英

How can I update redux state in Reducer in ReactJS?

Please know that I am new to ReactJS with Redux.

I have list of passengers, and each passenger has list of flights. I would like to update the flight property, checkedIn with the action property isCheckedIn . How can I achieve that with in reducer?

reducer.js

export default function passengerReducer(
  state = initialState.passengers,
  action
) {
  switch (action.type) {
    case types.LOAD_PASSENGERS_SUCCESS:
      return action.passengers;
    case types.UPDATE_PASSENGER_SUCCESS:
      console.log("action ", action.passengerData.passengerId);
      console.log("state ", state);
      return state
        .filter(x => x.id == action.passengerData.passengerId)
        .map(f => {
          f.flights[0].checkedIn = action.passengerData.isCheckedIn
        });

    default:
      return state;
  }
}

The state contains array of objects. Each object also contains flights . At the moment, I am only focusing the first flight with in flights array.

在此处输入图片说明

The action contains isCheckedIn property. I would like to update checkedIn property of the flights with isCheckedIn property from action.

在此处输入图片说明

So this is the piece of code in question I presume:

 case types.UPDATE_PASSENGER_SUCCESS:
  console.log("action ", action.passengerData.passengerId);
  console.log("state ", state);
  return state
    .filter(x => x.id == action.passengerData.passengerId)
    .map(f => {
      f.flights[0].checkedIn = action.passengerData.isCheckedIn
    });

You're (a) filtering the array only for the element you want to change, and (b) mapping that but not returning anything from your map function

Just (a) alone is bad -- you're going to change your entire state to only include the filtered items? I don't think that's what you intended. But then (b) means you're returning an array full of undefined

What you want to do, instead, is create a new array, var newArray = state.slice(0);

Then, find the index of the item you want to change the checked_in property of,

var index = newArray.findIndex(x => x.id == action.passengerData.passengerId);
var newPassenger = Object.assign({}, newArray[index]);
newPassenger.flights[0].checkedIn = action.passengerData.isCheckedIn;
newArray[index] = newPassenger;
return newArray;

So you've found the item you wanted to change, changed it, put it back in the array (this is the immutable way to do things, I think), and then returned the FULL array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM