简体   繁体   English

反应 state 变化时更新变量

[英]Update variable when react state changes

I am trying to update a variable when the scores state changes.scores state 发生变化时,我正在尝试更新一个变量。 At the moment I have a function inside a useEffect hook which calculate the sum of the scores array and updates the global totalScore variable.目前,我在useEffect挂钩中有一个 function,它计算得分数组的总和并更新全局 totalScore 变量。 For some reason the totalScore variable doesn't seem to be updating and displaying correctly on the screen - it just stays at 0.出于某种原因, totalScore变量似乎没有在屏幕上正确更新和显示——它只是停留在 0。

let totalScore = 0
const [scores, setScores] = useState([])

useEffect(() => {
  scores.forEach((score) => {
    totalScore += score
  }
}, [scores])

return (
  <>
    <p>{totalScore}</p>
  </>
)

Issue问题

For some reason the totalScore variable doesn't seem to be updating and displaying correctly on the screen - it just stays at 0.出于某种原因,totalScore 变量似乎没有在屏幕上正确更新和显示——它只是停留在 0。

This is because the useEffect hook runs after the component has rendered to the DOM.这是因为useEffect钩子在组件渲染到 DOM之后运行。 The totalScore variable was updated, but React needs another rerender to get it to the DOM. totalScore变量已更新,但 React 需要另一个重新渲染才能将其获取到 DOM。

Suggested Solution建议的解决方案

Since it's derived "state" from the scores state, it would be better to just compute the totalScore from the scores state in the component render.由于它是从scores state 派生的“状态”,因此最好只从组件渲染中的scores state 计算totalScore

const [scores, setScores] = useState([]);

const totalScore = scores.reduce((total, score) => score + total, 0);

return (
  <>
    <p>{totalScore}</p>
  </>
);

You can memoize totalScore with the useMemo hook if necessary.如有必要,您可以使用totalScore挂钩记忆useMemo

const totalScore = useMemo(() => {
  return scores.reduce((total, score) => score + total, 0);
}, [scores]);

You need to have totalScore in your state for it to get updated.您需要在totalScore中输入 totalScore 才能更新。

const [totalScore, setTotalScore] = useState(0)
const [scores, setScores] = useState([])

useEffect(() => {
   let ts = 0;
   scores.forEach((score) => {
      ts += score
   }
   setTotalScore(ts);
}, [scores])

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

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