简体   繁体   English

State 没有立即反映在反应挂钩中

[英]State is not reflecting immediately in react hooks

I am learning hooks.我正在学习钩子。 I am trying to update state but it's not reflecting immediately.我正在尝试更新 state,但它没有立即反映出来。 Here is my code.这是我的代码。

const Test = (props) => {
    const [score , setScore] = useState(0);
    const [count , setCount] = useState(0);
    const [total, setTotal] = useState(0);
 
const playerBallClick= ()=> {
        setCount(count+1);
        setScore(Math.floor(Math.random() * 10));
        setTotal(total + score);
    }

return (
        <div>
            <button onClick={playerBallClick}>Ball</button>
    {/* <p>Total score is - {totalscore}</p> */}
        </div>
    )
}

How can I update Total immediately onclick on Ball button.如何在 Ball 按钮上立即更新 Total onclick。

Score is a stale closure try the following instead: Score 是一个陈旧的闭包,请尝试以下操作:

const playerBallClick = () => {
  setCount(count + 1);
  const newScore = Math.floor(Math.random() * 10);
  setScore(newScore);
  setTotal(total => total + newScore);
};

You can use useEffect hook like so,你可以像这样使用 useEffect 钩子,

useEffect(() => {
   setTotal(total + score);
}, [count]);

So everytime count state changes, this hook will be called updating your total state.所以每次计算 state 变化时,这个钩子都会被调用来更新你的总数 state。

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

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