redux 使用filter方法后,即使满足所有条件,也无法设置属性的值

3npbholx  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(107)
const eventSeatSelectCallback = (
    
   
    SeatPrice,
    FlightNumber,
    SegmentKey
    
  ) => {
    var postObject = { ...state.post };
      postObject.IsSeatSelected = true;

      postObject.AirPassengerList.filter(
          (x) =>
              x.FlightNumber == FlightNumber.toString() &&
              x.SegmentKey.toString() == SegmentKey.toString() &&
              x.IsSelected == true
      )[0].SeatPrice = SeatPrice;
`
    dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });
  };

上面的行在控制台中给出错误,如未捕获的TypeError:无法设置未定义(设置“SeatPrice”)的属性我正在尝试将AirPassengerList.SeatPrice的值设置为SeatPrice
我想将对象AirPassengerList.SeatPrice的值设置为参数SeatPrice的值

hzbexzde

hzbexzde1#

您可以通过索引更新元素

const eventSeatSelectCallback = (
    SeatPrice,
    FlightNumber,
    SegmentKey
    
  ) => {

      var postObject = { ...state.post };

      postObject.IsSeatSelected = true;

      const passengerIndex = postObject.AirPassengerList?.findIndex(
          (x) =>
              x.FlightNumber == FlightNumber.toString() &&
              x.SegmentKey.toString() == SegmentKey.toString() &&
              x.IsSelected == true
      );
 
      // update if item is found
      if (passengerIndex !== -1) {
         postObject.AirPassengerList[passengerIndex].SeatPrice = SeatPrice;
         // do you need to updated this only after price update
         // dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });
      }   

      dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });  

  };

希望能有所帮助

相关问题