如何让状态在一段时间后消失(React)?
How to make a state disappear after some time (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
Return 声明
<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>
);
}
我在 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
Return 声明
<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>
);
}