جواب «Hits and Misses» چالش 4 از جلسهی 34
سؤال
state این بازی یک شیء با score و lives است. دکمهها سفارش میفرستند، ولی reducer هنوز هیچ کاری نمیکند. دو سفارش را بنویس:
- "hit": مقدار action.points را به score اضافه کند.
- "miss": یکی از lives کم کند.
یادت باشد: با ...state یک شیء تازه برگردان.
راهنما
if (action.type === "hit") { return { ...state, score: state.score + action.points }; } و برای "miss": return { ...state, lives: state.lives - 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 { useReducer } from "react";
import { createRoot } from "react-dom/client";
function reducer(state, action) {
if (action.type === "hit") {
return { ...state, score: state.score + action.points };
}
if (action.type === "miss") {
return { ...state, lives: state.lives - 1 };
}
return state;
}
function App() {
const [game, dispatch] = useReducer(reducer, { score: 0, lives: 3 });
return (
<div>
<p id="score">Score: {game.score}</p>
<p id="lives">Lives: {game.lives}</p>
<button id="hit" onClick={() => dispatch({ type: "hit", points: 10 })}>Hit</button>
<button id="bonus" onClick={() => dispatch({ type: "hit", points: 50 })}>Big hit</button>
<button id="miss" onClick={() => dispatch({ type: "miss" })}>Miss</button>
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن