简体   繁体   中英

Only one element is added to the array

The code is supposed to add 6 random elements to an array from another array, but for some reason it only adds it once `

  let [cubs, setcubs] = useState([
    {id:1,title:1, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png"},
    {id:2,title:2, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/2.png"},
    {id:3,title:3, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/3.png"},
    {id:4,title:4, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/4.png"},
    {id:5,title:5, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/5.png"},
    {id:6,title:6, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png"},
  ])
  
  let [cubikinapole, setcubikinapole] = useState([

  ])
  
  function sheker(){
    for(let i=0;i<6;i++){
      let randomcub = Math.floor(Math.random() * (6 - 0) + 0)
      let obj = {
        id: new Date().valueOf(),
        title: cubs[randomcub].title,
        img: cubs[randomcub].img
      }
      setcubikinapole([...cubikinapole, obj])
    }
    }

`

Tried the push method but it throws errors

Store the value in temp array until loop is finished and then update the store

function sheker(){
    const list = []
    for(let i=0;i<6;i++){
      let randomcub = Math.floor(Math.random() * (6 - 0) + 0)
      let obj = {
        id: new Date().valueOf(),
        title: cubs[randomcub].title,
        img: cubs[randomcub].img
      }
      list.push(obj)
    }
    
    setcubikinapole(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