React setState 即使在 useEffect 挂钩中也不更新状态?

React setState does not update state even in useEffect hook?

所以我正在制作一个每秒更新一次的工资计数器。我在 useEffect 挂钩中设置了一个 setInterval 计时器,以使用 setState 更新我的 "currentSalary","currentSalary" 的值不断更新,但当我记录该值时,它始终为 0。我无法换行我的头脑围绕着这个。以前从未遇到过设置状态的问题。

关于我做错了什么有什么想法吗?

 function App() {
  //State
  const [date, setDate] = useState();
  const [salaryPerHour] = useState(145);
  const [salaryPerSecond] = useState(salaryPerHour / 60 / 60);
  const initialSalary = 0;
  const [currentSalary, setCurrentSalary] = useState(initialSalary);

  useEffect(() => {
    console.log("Use effect att App.js");
    if (!date) {
      setInterval(function() {
        updateDate();
        setCurrentSalary(prevCurrentSalary => prevCurrentSalary + salaryPerSecond);
        console.log(currentSalary);
      }, 1000);
    }
  });

currentSalary 是局部常量。它永远不会改变,这不是 setCurrentSalary 想要做的。相反,调用 setCurrentSalary 的目的是告诉 React 重新渲染组件。在下一次渲染中,将创建一个新的局部变量,并将获得新值。但是之前render的log语句看不到这个。

所以它正在更新值,您只是将日志语句放在一个没有用的地方。如果您想验证组件是否使用新值重新呈现,请将您的日志语句放在组件的主体中。

const [currentSalary, setCurrentSalary] = useState(initialSalary);
console.log('rendering with', currentSalary);

useEffect(() => {
  // ...

您可以尝试创建另一个 useEffect 挂钩,而不是在该 useEffect 挂钩中记录值,只要对状态 currentSalary

进行更新,它就是 运行

钩子看起来像这样:

useEffect(() => {
   console.log(currentSalary)
}, [currentSalary])