简体   繁体   中英

How do I store the current value from a useState variable in an array?

After an onClick event fires, I call the setInterval function which in turn calls a function to set the value for a variable picked randomly from an array of 4 values (4 different colors). I need to keep track of what values were randomly selected. When I try to access the value of the getter variable returned from the useState hook by pushing it to my colortracker array, I see in the console that it's only storing empty strings in the array.

I've tried passing the bgCol variable in as a props value. I've tried curly braces around bgCol. Have tried defining my array with the keywords let and var.

function ColoredBox(props){

    return(
      <div style={{backgroundColor: props.color, marginBottom: 20, width: 
       200, height: 200}}>      
      </div>
    );
}

function Button(props){
    const start = () => {
        setInterval(props.startGame, 2000);
        }
    return(
        <button onClick={start} style={{marginBottom: 50}} >Start 
        Game</button>
  );
}



function Game(){
    const [bgCol, setbgCol]= useState('');
    const arr = ['red', 'blue', 'yellow', 'black'];
    const colortracker = [];     
    const handleClick = () => {     

        setbgCol(arr[Math.floor(Math.random()*Math.floor(4))]);
        colortracker.push(bgCol); 
        console.log(colortracker);    

    }
        return(
        <div>
            <ColoredBox color={bgCol} />
            <Button startGame={handleClick} />
        </div>
            );
      }

ReactDOM.render(<Game />,mountNode);

Actual output is an array filling up with empty strings as the values for bgCol when I need it to be strings representing the colors picked out of the arr array.

Maybe your handleClick is getting the first value of bgCol that is an empty string

try this

const handleClick = () => {

        const randomBgCol = arr[Math.floor(Math.random()*Math.floor(4))];
        setbgCol(randomBgCol);
        colortracker.push(randomBgCol); 

        console.log(colortracker);    
    }

This might be an issue where setState is asynchronous. (The state changes after calling setState, not necessarily right after.)

You can use a local variable in your handleClick:

    const color = arr[Math.floor(Math.random()*Math.floor(4))]
    setbgCol(color);
    colortracker.push(color); 
    console.log(colortracker);    

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