首页 > 解决方案 > {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”?

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读