简体   繁体   中英

How to change the state of a const on React with useState?

I'm doing a jokenpô game with react and I need to make a scoreboard that start with the state of the player and the computer with 0 and changes when some of them wins the game I've made a function

 const handlePlacar = () =>{
    if(victory === 'You'){
      setPlacarPlayer(placarPlayer ++)
    }
    else if(victory === 'Computer'){
      setPlacarComputer(placarComputer ++)
    }
  }

and I'm calling this function as a prop in the component placar in App.js

      <Divs>
       <Placar computer={placarComputer} player={placarPlayer} handlePlacar={handlePlacar}/>
      </Divs>

the component Placar code

import React from 'react';
import {Table, TableHead, TableRow, TableCell, TableContainer, TableBody} from '@material-ui/core';

const Placar = (props) =>{


    return(
      
        <TableContainer>
        <Table>
          <TableHead>Placar</TableHead>
          <TableRow>
            <TableCell>Player</TableCell>
            <TableCell>Computer</TableCell>
          </TableRow>
          <TableBody>
            <TableRow>
              <TableCell>{props.player}</TableCell>
              <TableCell>{props.computer}</TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </TableContainer>
    )
}

export default Placar

But the state isn't changing. I tried it with useEffect but It didn't work too.

Problem is that new value of state depends on previous state value. So you can update call setPlacarComputer method with callback.

const [count, setCount] = useState(0);


setCount(previousCount => previousCount + 1);

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