在React Hooks中使用setTimeout更新状态值的方法如下:
const [count, setCount] = useState(0);
const updateCount = () => {
setTimeout(() => {
setCount(count + 1);
}, 3000);
};
<button onClick={updateCount}>Update Count</button>
完整的示例代码如下:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const updateCount = () => {
setTimeout(() => {
setCount(count + 1);
}, 3000);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={updateCount}>Update Count</button>
</div>
);
};
export default MyComponent;
这样,当用户点击"Update Count"按钮时,组件将等待3秒后更新状态值并重新渲染。
领取专属 10元无门槛券
手把手带您无忧上云