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

#sh(javascript){{
** 元のuseReducerのコード [#jfb9e2da]

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

}}
** userReducerをラップしたカスタムフックのコード [#a85dc5d3]

 import React, { useReducer } from 'react';
 import ReactDOM from 'react-dom';
 
 function useCounter() {
   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,
     }
   );
 
   return [state, dispatch];
 }
 
 const App = () => {
   const [state, dispatch] = useCounter();
 
   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>
   );
 };
 
 ReactDOM.render(<App />, document.getElementById('root'));


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