首页 > 解决方案 > 获取 onClick() 函数中的最新值

问题描述

我的应用程序是一个计数器。

import React, {useState} from "react";

 function App() {
  const [count, setCount] = React.useState(0);
  const add = () => {
    setCount(count+1)
    console.log(count) // Here I want to get the updated count
  }
  return (
    <div className="App">
      <h1>Hello {count}</h1>
      <button onClick={add}>ADD</button>
    </div>
  );
}

问题是我无法获得count内部add函数的值,我只能获得以前的值。我知道这是因为 useState 是异步的。但是如何在add不使用 useEffect 的情况下获取函数内部的更新值?沙盒链接:https ://codesandbox.io/s/brave-feynman-k5b73?file=/src/App.js:0-377

标签: reactjs

解决方案


如果您正在更新状态并且新状态取决于先前的状态,那么您应该以这种方式更新它:

  const add = () => {
    setCount(prevCount => prevCount + 1);
  }

关于useEffect

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

每次计数更改时都会运行上面的代码,但是由于您说过有关调度操作的内容,并且您不想每次可以有条件地执行操作时都调度它:

useEffect(() => {
 if(count === 5) {
   console.log('Don't dispatch anything here');
 } else {
   console.log('Dispatch here');
 }
}, [count])

推荐阅读