جواب «Find the Bugs» چالش 6 از جلسهی 27
سؤال
این ثانیهشمار روی 0 میماند. دو اشتباه دارد:
- تمیزکاری درست نوشته نشده و تایمر همان اول خاموش میشود.
- حتی اگر تایمر کار کند، عدد از 1 بالاتر نمیرود.
هر دو را درست کن تا هر ثانیه یکی زیاد شود.
راهنما
تمیزکاری باید تابع باشد: return () => clearInterval(timer);. داخل تایمر هم شکل تابعی را بنویس: setSeconds((old) => old + 1);
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
function App() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setSeconds((old) => old + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <h1 id="sec">{seconds}</h1>;
}
createRoot(document.getElementById("root")).render(<App />);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن