簡體   English   中英

React redux 更新對象列表嵌套對象

[英]React redux update a list of objects nested objects

我試圖在我的 redux 商店中創建這個結構,具有添加用戶的功能,努力更新結構以向用戶添加汽車,我傳遞對象認為我需要在狀態上做一個映射,但它不能正常工作

 // main object im trying to build const inventory = [ { id: 1, name: "Paul", cars: [ { model: "Ford", year: "1995", }, { model: "BMW", year: "2010", }, ], }, { id: 2, name: "Simon", cars: [ { model: "Vauxhall", year: "2022", }, { model: "VW", year: "2001", }, ], }, ]; // object that gets sent to the store const addUser = (content) => ( { type: 'ADD_USER', payload: { id : 1, name : 'George', cars : [] } } ) const carOptions = (content) => ( { type : "ADD_CAR", payload : { model: "Porsche", year: "2009" } } ) This is my reducer main issue appears in ADD_CAR const carReducer = ( state = [], action) => { switch(action.type) { case 'ADD_USER': return [...state,action.payload] case 'ADD_CAR': return state.map((item) => item.id === 1 ? { ...item, cars: item.cars.concat([ ...state, action.payload ]) } : item ); default: return state; } }

我認為您應該指定要將汽車添加到哪個用戶。 您的 ADD_CAR 有效負載可能如下所示:

{ userId, carOptions: { model: "Porsche", year: "2009" } }

在 reducer 中,您將首先通過 userId 找到用戶,然后將汽車添加到該用戶,就像這樣:

return state.map((user) =>
    user.id === action.payload.userId
      ? { ...user, cars: [...user.cars, action.payload.carOptions] }
      : user
  );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM