简体   繁体   中英

for-loop in function call with state hooks - React

I want my function to roll 5 dices and store them in my dices state.

In the recent version, i am only storing one object for the next click, but i made the for loop to generate 5 dices at once, how can i store the previous dce object(s) for the next iteration in the for loop?

import './App.css';
import Subgroup from './Subgroup'
import React, {useState} from 'react'


function App() {

  const [numberRolls, setNumberRolls] = useState(3);
  const [dices, setDices] = useState([]);


  return (
    <div className="App">
        <Subgroup 
          numberRolls = {numberRolls}
          setNumberRolls = {setNumberRolls}
          dices = {dices} 
          setDices = {setDices}
        />
    </div>
  );
}

export default App;
import React from 'react'


const Subgroup = ({numberRolls, setNumberRolls, dices, setDices}) => {

    const rollTheDice =  () => {
        if(numberRolls > 0) {
            setNumberRolls(numberRolls - 1);

            for(let i = 0; i < 5; i++) {
                setDices([...dices,                 // i think sth should be different here????
                    {id: Math.random()*100, 
                     number: Math.ceil(Math.random()*6)-1, 
                     selected: false} 
                ])
            }
        }
        console.log(dices)
    }

    return (
        <div> 
            <button onClick={ rollTheDice }>blablabala </button>
        </div>
    )
}

export default Subgroup;

Try saving the result in an array, then set the state, something like:

const result = [];

for(let i = 0; i < 5; i++) {
  result.push({
    id: Math.random() * 100, 
    number: Math.ceil(Math.random() * 6) -1, 
    selected: false
  });
}
  
setDices(prev => [...prev, ...result]);

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