React-Redux(3)

최권능·2022년 3월 6일
0

개발스터디

목록 보기
4/7

사용법

1.redux, react-redux 설치

yarn add redux
yarn add react-redux

한번에 설치 하려면 중간에 띄어쓰기하면 됨
yarn add redux react-redux

2.store 생성

createStore불러오기

import {createStore} from 'redux'

store 생성

const store = createStore();

createStore는 필수 인자로 reducer를 받음

3.reducer 생성

reducer는 현재 state와 action값을 인자로 받아 작업하고 새로운 state를 return 함
createStore의 필수인자로 reducer전달

function reducer(state, action){
	return
}

const store = createStore(reducer);

3-1.reducer state 초기값 설정 및 불변성 대응

reducer를 처음 호출 할때 state 값은 undefined로 값이 없기때문에 대응로직 생성
state 값을 부수효과로 변경하면 예상치 못한 오류 발생 가능성 높음
현재 state 값을 newState로 복사 후 사용

function reducer(state, action){
	if(state === undefined){
    	return {
        	상태명: 초기값
        }
    const newState = {...state};
    return newState;
}

const store = createStore(reducer);

4.Provider, useSelector, useDispatch, connect

react-redux의 대표기능 4가지

4-1 Provider

store에 정의 한 state를 어떤 컴포넌트에 제공 할 것인가 정해서 감싸주는 기능
감싼 컴포넌트의 하위 컴포넌트들도 store에 접근가능
Provider에 필수로 props값 store={store} 포함

  • ex) component2,3 에만 store를 제공 할 경우
export default function App() {
	return (
    	<div>
        	<component1 />
            <Provider store={store}>
            	<component2 />
            	<component3 />
            </Provider>
            <component4 />
        </div>
    )
}

4-2 useSelector

Provider 안에 있는 컴포넌트에서 store state에 접근하게 해주는 함수
useSelector는 함수를 인자로 받음

fucntion 콜백함수(state){
	return state.상태명
}

const 변수명 = useSelector(콜백함수);
-----------------------------------
화살표 함수로 변경해서 간단히 사용하가능

const 변수명 = useSelector(state => state.상태명)

컴포넌트에서 useSelector로 가져온 변수를 사용

  • ex) useSelector(state => state.상태명) 으로 가져온 '상태명'사용
function component9(props) {
  const 사용할변수명 = useSelector(state => state.상태명)
  return (
    <div>
      <h1>불러온 상태값 : {사용할변수명}</h1>
    </div>
  );
}

4-3 useDispatch

Provider 안에 있는 컴포넌트에서 dispatch에 접근하게 해주는 함수
보통 이벤트를 발생시킬때 사용함
dipatch가 호출되면 reducer가 호출됨

  • ex) type값이 PLUS인 action을 dispatch로 전달해서 reducer호출
const dipatch = useDispatch();
-------------------------------

function component10(props) {
  const dipatch = useDispatch();
  return (
    <div>
      <input 
      	type="button" 
        value="+" 
        onClick={()=>{
        	dispatch({type:'PLUS'})
            }}
       ></input>
    </div>
  );
}

dispatch로 전달한 action값을 참조해서 reducer에 기능 작성

  • ex) type값이 PLUS일경우 newState의 state(아래 예제에서는 '상태명')를 한번 더해라
function reducer(state, action){
	if(state === undefined){
    	return {
        	상태명: 1
        }
    const newState = {...state};
    if(action.type === 'PLUS'){
    	newState.상태명++
    }
    return newState;
}

const store = createStore(reducer);

4-4 connect(생략)

Tip.

react-redux를 사용해서 변경한 state 값은 해당 컴포넌트에서만 변하는 값으로
다른 컴포넌트를 재랜더링 하지 않음

profile
초보개발자

0개의 댓글