无法在函数中使用 useState 获取第一个值
我需要根据数据值显示文本。通过运行代码,我希望看到单击按钮后可以显示“Test1:1”,但我不能。有什么方法可以实现这一点吗?
以下是包含代码的示例沙箱链接。 https://codesandbox.io/s/restless-wildflower -9pl09k?file=/src/Parent.js
export default function Parent(props) {
const [data, setData] = useState(0);
const onClick = () => {
setData(1);
console.log(data);
setData(2);
};
return (
<>
<button onClick={onClick}> Click here </button>
{data === 1 ? <div>Test1: {data}</div> : <div>Test2: {data}</div>}
</>
);
}
I need to show the text according to the data value. By running the code, I want to see the 'Test1: 1' can be shown after I clicked the button, but I can't. Any method to make this happen?
Below is a sample sandbox link including the code.
https://codesandbox.io/s/restless-wildflower-9pl09k?file=/src/Parent.js
export default function Parent(props) {
const [data, setData] = useState(0);
const onClick = () => {
setData(1);
console.log(data);
setData(2);
};
return (
<>
<button onClick={onClick}> Click here </button>
{data === 1 ? <div>Test1: {data}</div> : <div>Test2: {data}</div>}
</>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
useState
返回的setState
函数不会直接更新状态。相反,它用于发送 React 在下一次异步状态更新期间将使用的值。console.log
是一种效果,因此如果您想查看每次更改时记录的data
,您可以使用 React.useEffect。 运行下面的代码并单击0按钮几次以查看浏览器中的状态变化和效果。您的评论讨论了网络请求示例。可以设计自定义挂钩来适应复杂的用例并使您的组件易于编写。
The
setState
function returned byuseState
does not directly update the state. Instead it is used to send the value that React will use during the next asynchronous state update.console.log
is an effect so if you want to seedata
logged every time it is changed, you can use React.useEffect. Run the code below and click the 0 button several times to see the state changes and effects in your browser.Your comment talks about a network request example. Custom hooks can be designed to accommodate complex use cases and keep your components easy to write.
console.log(data)
没有反映最新数据的原因是 React 管理状态。对 setState() 的调用是异步的,如果您想依赖状态的新值,正确的方法是传递旧状态的函数,返回当前状态。 参考。文档The reason the
console.log(data)
did not reflect the latest data is because of the React manages state. Calls to setState() are asynchronous, and if you want to rely on the new value of the state, the correct way is to pass a function of old state, returning the current state. ref. documentation