简体   繁体   中英

setState containing object=>array=> objects

What i have is

const [productData, setproductData] = useState({
    title: "",
    description: "",
    price: "",
    selectedFile: "",
    images: [{ _id: "", urls: "" }],
  });

How i will change the values inside IMAGES object. I want to change id and Urls.

I have tried the following methods but unsuccessful.

  setproductData({
    ...productData,
    images: [...productData.images._id, i],  //where i is any id or number
  });

but when i try to execute it it says productData.images.id is not iterable. Can any help plz...

try this out

 setproductData({
    ...productData,
    images: [{...productData.images[0], _id: i}], 
  });

if you want to modify selected id just use

    setproductData({
        ...productData,
        images: productData.images.map((image) => {
          if (image._id === i) return {...image} // modify here
          return image
        }), 
    });

Where newId is your new _id, and newUrls is your new urls

setProductData(prev => ({
  ...prev,
  images: [...prev.images, {_id: newId, urls: newUrls}]
})
    

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