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

A New Order چالش 1 از جلسه‌ی 34، آسان

دکمه‌ی -1 سفارش { type: "sub" } را می‌فرستد، ولی reducer این سفارش را نمی‌شناسد و عدد عوض نمی‌شود.
در reducer یک if تازه برای سفارش "sub" بنویس که یکی از state کم کند.

<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") {
    return state + 1;
  }
  return state;
}

function App() {
  const [count, dispatch] = useReducer(reducer, 0);
  return (
    <div>
      <p id="count" className="big">{count}</p>
      <button id="plus" onClick={() => dispatch({ type: "add" })}>+1</button>
      <button id="minus" onClick={() => dispatch({ type: "sub" })}>-1</button>
    </div>
  );
}

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

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 34: useReducer و اشتباه‌های رایج · چالش بعدی: Send the Order

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