为什么useState不能正常工作或者我错过了一些如此明显的东西?



我是新手,只是阅读了关于useState的文档。所以我开始在操场上尝试,但看起来不起作用。当我尝试记录temp的值时,它是空的。在下面的例子:

链接到游乐场

阅读useEffect钩子以便打印状态值。setState为异步。如果你想打印新的temp值,你需要使用useEffect钩子并在useEffect上放置一个依赖项temp。因此,每当temp更改时,useEffect将运行回调。

更多信息:https://reactjs.org/docs/hooks-effect.html

import React, {useState, useEffect} from 'react';
export function App(props) {
const [temp, setTemp] = useState('')
const handleClick = () => {
setTemp('Value changes')

}
useEffect(() => {
console.log("Temp val is ",temp)
}, [temp])
return (
<div className='App'>
<h1>Hello React.</h1>
<h2 onClick={()=> handleClick()}>Should set temp after clicking here </h2>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
// Log to console
console.log('Hello console')

https://playcode.io/893227

相关内容

最新更新