[React] Redux 사용해보기 - 2 (useSelector, useDispatch)

JoGabi·2021년 12월 9일
0

React

목록 보기
5/8
post-thumbnail

이유

redux store에 있던 state를 꺼내쓰려면
state를 props화 해주는 함수 어쩌구를 파일밑에 첨부해야 했다.
하지만 코드가 길어져서 짜증난다.
그럴 땐 useSelector Hook을 쓰는 방법이 있다.

사용법

하단 export 부분은 기존대로

export default Cart

useSelector, useDispatch 를 연결시킴

import { useSelector, useDispatch } from 'react-redux'

그리고 함수 안에 변수로 선언해준다.
state 변수명으로
dispatch 도 변수명으로 줌

function 함수( props ) {
 const state = useSelector( state => state )
 const dispatch = useDispatch()
 return(
   <div>
   state.reducer.map( ( item, index ) => {})
   <button onClick={() => {
   dispatch( { type: 'plus', payload: { id: item.id, 			quan: item.quan } } )
 	}}>증가</button>

   </div>
 )
}
profile
서울에서 프론트엔드 개발자로 일하고 있는 Gabi 입니다. 프론트엔드: Javascript, React, TypeScript 에 관심이 있습니다.

0개의 댓글