بتل کد Battle Codeدارد باز می‌شود…

Hits and Misses چالش 4 از جلسه‌ی 34، متوسط

state این بازی یک شیء با score و lives است. دکمه‌ها سفارش می‌فرستند، ولی reducer هنوز هیچ کاری نمی‌کند. دو سفارش را بنویس:
- "hit": مقدار action.points را به score اضافه کند.
- "miss": یکی از lives کم کند.

یادت باشد: با ...state یک شیء تازه برگردان.

<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) {
  // your code here
  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>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 34: useReducer و اشتباه‌های رایج · چالش بعدی: The Team List

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js