• 追加された行はこの色です。
  • 削除された行はこの色です。
#author("2021-03-21T11:24:21+09:00","default:ryuichi","ryuichi")
* useReducer [#r2ec74ea]

#sh(javascript){{

 import React, { useState, useReducer } from 'react';
 import ReactDOM from 'react-dom';
 
 const App = () => {
   const [state, dispatch] = useReducer(
     (state, action) => {
       switch (action.type) {
         case "ADD": {
           return { ...state, count: state.count + 1 };
         }
         case "SUBTRACT": {
           return { ...state, count: state.count - 1 };
         }
         default: {
           return state;
         }
       }
     },
     {
       count: 0,
     }
   );
 
   let { count } = state;
 
   const add = () => {
     dispatch({ type: "ADD" });
   };
 
   const subtract = () => {
     if (count > 0) {
       dispatch({ type: "SUBTRACT" });
     }
   };
 
   return (
     <div>
       <button onClick={subtract}>-</button>
       <div>{count}</div>
       <button onClick={add}>+</button>
     </div>
   );
 };

}}



トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS