简体   繁体   中英

Updating a nested state Object in React Native?

I am creating a shopping list application that gives a user to ability to create a shopping list. Each shopping list that the user creates has the following properties:

key name budget listItem

Nested within the listItem property is an array of objects of list items.

Each list item has the following properties: id: name: price:

Here is a code snippet:

const [shoppingLists, setShoppingList] = useState([
    {key: '1', name: `Khari's Shopping List`, budget: 200, listItems:[
            {id: Math.random().toString(), name:"butter", price:2.00},
            {id: Math.random().toString(), name:"milk", price:2.00},
            {id: Math.random().toString(),  name:"cereal", price: 3.00},
            {id: Math.random().toString(),  name:"chicken", price: 4.00},
            {id: Math.random().toString(),  name:"spaghetti", price: 5.00},
        ], },
    {key: '2', name: `Janae's Shopping List`, budget: 500, listItems:[
            {id: Math.random().toString(), name:"butter2", price:0.00},
            {id: Math.random().toString(), name:"milk2", price:0.00},
            {id: Math.random().toString(),  name:"cereal3", price: 0.00},
            {id: Math.random().toString(),  name:"chicken2", price: 0.00},
            {id: Math.random().toString(),  name:"spaghetti2", price: 0.00},
        ], },

])

What I wish to do is update the price property that is nested in the list item when a user enters a number in the text input. Any ideas on how I can achieve this?

When a user enters a number in a text input I what to update the price property in the list item array based on the id. I am not sure where to begin and I am hoping for some guidance. Thanks for any help that you can offer.

In functional component state updates you need to shallowly copy the existing state into a new object, updating the specific object. With more deeply nested state you need to also copy the nested state and update.

Given a specified key , id , and updated price

setShoppingList(lists =>
  lists.map(list =>
    list.key === key
      // Key matches, spread existing state and update list items array
      ? {
          ...list,
          listItems: list.listItems.map(item =>
            item.id === id
              // Item id match, spread existing item and update price
              ? {
                  ...item,
                  price
                }
              // No item id match, pass existing item
              : item
          )
        }
      // No key match, pass existing list
      : list
  )
);

编辑更新嵌套状态

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