javascript - {foo}、{ () => {foo()} } 和 { () => {foo(var1)} } 之间的区别?
问题描述
基本上,我试图通过在另一个函数中调用 setter 方法来改变 React 的状态。前两个方法改变了我的状态,但第三个没有立即改变(我将所有调用绑定到一个 onClick 事件,然后只是在按钮上火腿)
const [var1, setVar1] = useState(null)
const foo = () => {
console.log(var1)
setVar1("hello world")
console.log(var1)
}
...<button onClick={foo}>test</button> //logs("hello world" ; "hello world")
...<button onClick={() => {foo()}}>test</button> //logs("hello world" ; "hello world")
...<button onClick={() => {foo("test")}}>test</button> //logs(null ; null) //pressing again log("hello world"; "hello world")
有趣的是,如果我将 foo 更改为接受并使用变量,第三次调用将记录(“hello world”,“hello world”),但如果我不使用该变量,它会在第一次尝试时返回 null,然后在第二次点击它会显示正在改变的状态
const foo2 = (testVar) => {
console.log(var1)
setVar1(testVar)
console.log(var1)
}
...<button onClick={() => {foo2("hello world")}}>test</button> //logs("hello world"; "hello world")
const foo3 = (testVar) => {
console.log(var1)
setVar1("the inner hello world")
}
...<button onClick={() => {foo2("hello world")}}>test</button> //logs(null; null) // second click onward logs ("the inner hello world"; "the inner hello world")
另外,当我们讨论这个话题时,有没有人知道为什么它甚至在 setter setVar1() 被调用之前就记录“hello world”?
解决方案
推荐阅读
- azure-devops - 如何以及在何处与 CI 共享 Git-Crypt 的私钥以解密加密文件?
- git - git - 更改子模块 URL 后出错 - 致命:需要单个修订
- javascript - 为什么有些 JavaScript 需要网络服务器?
- docker - 无法从分类帐中读取块号 3,因为在索引中找不到条目,正在跳过...?
- django - Django:validate_date() 缺少 1 个必需的位置参数:'value'
- c# - 如何使用最短路径返回多个节点?
- spring - 错误:在 Spring boot kotlin 新项目中找不到或加载主类
- python - Python face_recognition 数据集质量
- django - Django 3.0 + 频道 + ASGI + TokenAuthMiddleware
- bash - 使用bash将表格转换为文本文件中的逗号分隔