reactjs - 获取 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
解决方案
如果您正在更新状态并且新状态取决于先前的状态,那么您应该以这种方式更新它:
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])
推荐阅读
- amazon-web-services - boto3 s3角色arn
- youtube - YouTube 应用中的视频开始/结束时间
- html - 来自 HTML 表的 Powershell 变量一值
- swift - 如何在 Swift 中更改 iOS 弹出窗口中箭头的背景颜色?
- angular - Angular:刷新页面似乎激活了 ngOnInit,但没有激活 OnDestroy
- php - 将值从 php 页面传递到来自其他页面的模式
- angular - Angular 6 + Electron 从 api 保存图像以获得更好的性能
- python - 为什么我的psychopy.visual.TextStim 中不能包含“£”符号?
- c# - 协助编写循环以返回数据
- c# - GKE 访问服务