react中reduce基本使用

发布时间 2023-06-04 14:27:28作者: 前端那点事
import React ,{useReducer}from 'react';
import './App.css';


const App =() =>{


const reduce =(state,action)=>{

  const actionFn = {
     add:function(){
       return {
         ...state,
         count:state.count+1
       }
     }
   }
 
   return actionFn[action.type]();
 
 }
 
 const [state,dispatch] = useReducer(reduce,{count:0})
 
 const addCount = () =>{
   dispatch({type:'add'})
 }

  return (
     <div>
        <div>{state.count}</div>
        <button onClick={addCount}>+1</button>
     </div>

  );
}

export default App;