Find the Bugs چالش 6 از جلسهی 34، سخت
این شمارنده باید با +1 یکی زیاد و با Reset صفر شود، ولی عدد روی صفحه تکان نمیخورد. برنامه دو اشتباه دارد؛ هر دو را درست کن.
راهنمایی: به شکل سفارشی که دکمهی +1 میفرستد نگاه کن، و به اینکه reducer یک شیء تازه برمیگرداند یا همان قبلی را.
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.big { font-size: 40px; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useReducer } from "react";
import { createRoot } from "react-dom/client";
function reducer(state, action) {
if (action.type === "add") {
state.count = state.count + 1;
return state;
}
if (action.type === "reset") {
return { count: 0 };
}
return state;
}
function App() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p id="count" className="big">{state.count}</p>
<button id="plus" onClick={() => dispatch("add")}>+1</button>
<button id="reset" onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 34: useReducer و اشتباههای رایج
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js