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

جواب «The Team List» چالش 5 از جلسه‌ی 34

سؤال

فهرست بازیکن‌های تیم را با useReducer بساز. کادر و دکمه‌ها آماده‌اند، ولی team یک آرایه‌ی خالی ثابت است.
1. تابع reducer را بنویس: با سفارش "add" اسم action.name را به آخر یک آرایه‌ی تازه اضافه کند و با سفارش "clear" آرایه‌ی خالی برگرداند.
2. در App بنویس const [team, dispatch] = useReducer(reducer, []);
3. دکمه‌ی #add سفارش "add" را با name: text بفرستد و بعد کادر را خالی کند. دکمه‌ی #clear سفارش "clear" را بفرستد.

راهنما

در reducer: if (action.type === "add") { return [...state, action.name]; } و if (action.type === "clear") { return []; }. در add: dispatch({ type: "add", name: text }); و setText("");

یک جواب درست

<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, useReducer } from "react";
import { createRoot } from "react-dom/client";

function reducer(state, action) {
  if (action.type === "add") {
    return [...state, action.name];
  }
  if (action.type === "clear") {
    return [];
  }
  return state;
}

function App() {
  const [text, setText] = useState("");
  const [team, dispatch] = useReducer(reducer, []);

  function add() {
    dispatch({ type: "add", name: text });
    setText("");
  }

  return (
    <div>
      <input id="name" value={text} onChange={(e) => setText(e.target.value)} />
      <button id="add" onClick={add}>Add</button>
      <button id="clear" onClick={() => dispatch({ type: "clear" })}>Clear</button>
      <p id="n">Players: {team.length}</p>
      <ul id="team">
        {team.map((name, i) => (
          <li key={i}>{name}</li>
        ))}
      </ul>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن