IlanZiin

#040 EXERCÍCIO PRÁTICO COM USEREDUCER

Sep 17th, 2022
1,381
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.     const [state, dispatch] = useReducer(reducer, {
  6.         score_1: 0,
  7.         score_2: 0
  8.     })
  9.  
  10.     function reducer(state, action){
  11.         switch(action.type){
  12.             case 'SCORE1':
  13.                 return {
  14.                     score_1: state.score_1 + 1,
  15.                     score_2: state.score_2
  16.                 }
  17.  
  18.             case 'SCORE2':
  19.                 return {
  20.                     score_1: state.score_1,
  21.                     score_2: state.score_2 + 1
  22.                 }
  23.             case 'RESET':
  24.                 return {
  25.                     score_1: 0,
  26.                     score_2: 0
  27.                 }
  28.  
  29.             default:
  30.                 return state
  31.         }
  32.     }
  33.  
  34.     function incrementar1(){
  35.         dispatch({type: "SCORE1"})
  36.     }
  37.  
  38.     function incrementar2(){
  39.         dispatch({type: "SCORE2"})
  40.     }
  41.  
  42.     function reset(){
  43.         dispatch({type: "RESET"})
  44.     }
  45.  
  46.     return (
  47.         <>
  48.             <h1>React Hooks - useReducer</h1>
  49.             <hr />
  50.  
  51.             <h3>Player 1: { state.score_1 }</h3>
  52.             <h3>Player 2: { state.score_2 }</h3>
  53.  
  54.             <button onClick={incrementar1}>Player1</button>
  55.             <button onClick={incrementar2}>Player2</button>
  56.             <button onClick={reset}>Resetar</button>
  57.         </>
  58.     )
  59. }
  60.  
  61. export default App
Advertisement
Add Comment
Please, Sign In to add comment