简体   繁体   English

如何使用useState更改React上const的state?

[英]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我正在用 react 做一个 jokenpô 游戏,我需要制作一个记分牌,以玩家的 state 和 0 的计算机开始,当他们中的一些人赢得比赛时发生变化我做了一个 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我将这个 function 称为 App.js 中组件 placar 中的道具

      <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.但是 state 没有改变。 I tried it with useEffect but It didn't work too.我用 useEffect 试过了,但它也没有用。

Problem is that new value of state depends on previous state value.问题是 state 的新值取决于之前的 state 值。 So you can update call setPlacarComputer method with callback.因此,您可以使用回调更新调用 setPlacarComputer 方法。

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


setCount(previousCount => previousCount + 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM