简体   繁体   中英

How to use reducer in neasted array

trying to delete id:2 car from my mongodb database. using react redux, my question is how to check dispatch id equal to car id in reducer?

button <button onClick={this.handleDeleteCar(carID : data.id)>delete</button>

data log

carview:
       [ 
         { id: 5c7496f0def4602bf413ea9a,
            parentId: 5c7496f0def4602bf413ea97,
            car: [
                   {
                     id: 2,
                     name: bmw
                   },
                   {
                     id:3,
                     name: amg
                    }
                 ]
          }
        ]

reducer

case carConstants.car_DELETE_REQUEST:
return {...state,items: state.items.map(car =>car.id === action.id
        ? { ...car, deleting: true }
        : car
    )
  };

Use Array.prototype.filter()

return {
  ...state,
  items: state.items.filter((car) => car.id !== action.id)
}

EDIT:

In your case, you can use an Array.prototype.filter nested inside an Array.prototype.map:

return {
  ...state,
  carView: state.carView.map((view) => {
    return {
      ...view,
      car: view.car.filter(({ id }) => id !== action.id)
    }
  })
}

This can become quickly messy if you deal with deeply nested objects and it's a good idead to try to keep your state normalized in redux

Above answer using Array.filter is a good one, but if that won't fit your use case you can use a nested findIndex check.

 let state = [ { id: "5c7496f0def4602bf413ea9a", parentId: "5c7496f0def4602bf413ea97", car: [ { id: 4, name: "bmw" }, { id:5, name: "amg" } ] }, { id: "5c7496f0def4602bf413ea9a", parentId: "5c7496f0def4602bf413ea97", car: [ { id: 2, name: "bmw" }, { id:3, name: "amg" } ] } ]; const action = { type: 'example', id: 2 } const index = state.findIndex(({car}) => car.findIndex(({id}) => id === action.id) !== -1); if (index === -1) { // you would probably return current state here realistically throw new Error('no index'); } console.log(index); state = [ ...state.slice(0, index), ...state.slice(index + 1)]; console.log(state); 

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