如何使状态消失一段时间后(React)?



我在useState钩子中有一个状态,我想让它在特定的时间框架后消失。我尝试使用setTimeout(),但它不工作。

export const Profile = () => {
let { username } = useParams();
const [bio, setBio] = useState("");
const [country, setCountry] = useState("");
const [updated, setUpdated] = useState(""); // I am printing this 'updated' value in my return statement

返回语句

<h3>{updated}</h3> // I want this 'updated' text to disappear after 3 sec

以下列方式与useEffect()setTimeout()组合使用:

let timeoutId = null;
export function App(props) {
const [updated, setUpdated] = useState("");
useEffect(() => {
// if there's a message in updated
if(updated.length > 0) {
//remove previous timeout if any
if(timeoutId !== null) {
clearTimeout(timeoutId);
}
// create a timeout to remove it
timeoutId = setTimeout(() => setUpdated(""), 3000);
}

// cleanup
return () => {
if(timeoutId !== null) {
clearTimeout(timeoutId);
}
}
}, [updated])

return (
<div className='App'>
<button onClick={() => setUpdated("You have successfully did something!")}> setUpdated("You have successfully did something!") </button>
<hr />
{updated}
</div>
);
}

演示:https://playcode.io/895066

最新更新