IlanZiin

#039 USEREDUCER

Sep 17th, 2022
1,160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useReducer } from 'react'
  2.  
  3. function App(){
  4.  
  5.     // reducer
  6.     const [state, dispatch] = useReducer(reducer, {
  7.         valor: 1000,
  8.         mostrar: true
  9.     })
  10.  
  11.     // methods
  12.     function reducer(state, action){
  13.         switch(action.type){
  14.             case 'INCREMENTAR':
  15.                 return {
  16.                     valor: state.valor + 1,
  17.                     mostrar: state.mostrar
  18.                 }
  19.            
  20.             case 'VISIBILIDADE':
  21.                 return {
  22.                     valor: state.valor,
  23.                     mostrar: !state.mostrar
  24.                 }
  25.  
  26.             default:
  27.                 return state
  28.         }
  29.     }
  30.  
  31.  
  32.     return (
  33.         <>
  34.             <h1>React Hooks - useReducer</h1>
  35.             <hr />
  36.             <p>Valor: {state.valor}</p>
  37.             { state.mostrar && <p>Colocar visivel</p> }
  38.  
  39.             <button onClick={ () => { dispatch({type: 'INCREMENTAR'}) } }>Incrementar</button>
  40.             <button onClick={ () => { dispatch({type: 'VISIBILIDADE'}) } }>Mostrar/Esconder</button>
  41.         </>
  42.     )
  43. }
  44.  
  45. export default App
Advertisement
Add Comment
Please, Sign In to add comment