[React] react-redux

sese·2022년 12월 1일

새싹

목록 보기
35/39

redux 에 대한 기본적인 설명을 다음을 참고하자 👉🏻 [js]redux


redux 사용을 위한 라이브러리를 설치해준다

$ npm i redux react-redux

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { composeWithDevTools } from "redux-devtools-extension";
import PracticeDefault from './PracticeDefault';

// reducer 함수를 통해 state를 변경할 수 있다
function reducer(state, action) {
    if ( action.type == "DEPOSIT" ) return { money : state.money + Number(action.amount) };
    if ( action.type == "WITHDRAW" ) return { money : state.money - Number(action.amount) };
  	// 초기 state
    return { money : 0 };
}

// store를 생성할 때 reducer 함수를 넣어준다
const store = createStore(reducer, composeWithDevTools());

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <>
  		// state를 불러올 가장 최상위를 Provider로 감싸준다 
        <Provider store={store}>
            <PracticeDefault />
        </Provider>
    </>
);

PracticeDefault.js

import { useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import counterReducer from './store/counterReducer';

function PracticeDefault() {
    // useSelector를 통해 state를 가져올 수 있다
    const money = useSelector((state) => state.money);
    const count = useSelector((state) => state.count);

    return (
        <div style={{textAlign: 'center'}}>
            <h1>코딩온 은행</h1>
            <h3>잔액 : {money.money}</h3>
            <h3>카운트 : {count.count}</h3>
            <Button />
        </div>
    );
}

const Button = () => {

    const input = useRef();
    const dispatch = useDispatch();

    function deposit() {
     	// dispatch를 통해 reducer 함수를 실행시킨다
        dispatch({type: "DEPOSIT", amount: input.current.value});
    }

    function withdraw() {
        dispatch({type: "WITHDRAW", amount: input.current.value});
    }

    return (
        <div style={{display: 'flex', justifyContent: 'center'}}>
            <input type="text" ref={input} />
            <button onClick={deposit}>입금</button>
            <button onClick={withdraw}>출금</button>
            <button onClick={() => {dispatch({type: "INCREASE"})}}>INCREASE</button>
        </div>
    )
}

export default PracticeDefault;
profile
예전 글은 다크모드로 봐야 잘 보일 수도 있습니다.

0개의 댓글