useReducer

元のuseReducerのコード

 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>
   );
 };
 
 ReactDOM.render(<App />, document.getElementById('root'));

userReducerをラップしたカスタムフックのコード

 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

Last-modified: 2021-03-21 (日) 11:34:41