단순 코드 기록/RE: React

redux 기초

일일일코_장민기 2024. 5. 22. 23:16
728x90

 

전체 코드

더보기
import React, {useState} from "react";
import "./style.css";
import {createStore} from "redux";
import { Provider, useSelector, useDispatch, connect } from "react-redux";

const reducer = (currentState, action) => {
   
    if(currentState === undefined){
        return {
            number: 1,                  // number의 기본값을 1로 지정
        };
    }
    const newState = {...currentState};
    if(action.type === "PLUS"){
        newState.number++;
    }
    return newState;
}
const store = createStore(reducer);

export default function App(){

    return(
        <div id="container">
            <h1>Root</h1>
            <div id="grid">
                <Provider store={store}>
                    <Left1></Left1>
                    <Right1></Right1>
                </Provider>
            </div>
        </div>
    )
}

const Right1 = (props) => {
    return (
        <div>
            <h1>Right1</h1>
            <Right2></Right2>
        </div>
    )
}

const Right2 = (props) => {
    return (
        <div>
            <h1>Right2</h1>
            <Right3></Right3>
        </div>
    )
}

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

const Left1 = (props) => {
    return(
        <div>
            <h1>Left1</h1>
            <Left2></Left2>
        </div>
    )
}

const Left2 = (props) => {
    return(
        <div>
            <h1>Left2</h1>
            <Left3></Left3>
        </div>
    )
}

const Left3 = (props) => {
    const number = useSelector((state) => state.number);
    return(
        <div>
            <h1>Left3: {number}</h1>
        </div>
    )
}

 

1. Redux
- 원거리 state를 연결
ex) 말단 state와 root의 이벤트를 연결
- 이때 reducer를 통해 store에 있는 state를 어떻게 바꿀 것인지 결정하는 역할

redux를 쓰지 않고 연결할 경우
-> 컴포넌트마다 연결해주어야 함
import React, {useState} from "react";
import "./style.css";

export default function App(){

    const [number, setNubmer] = useState(1);

    return(
        <div id="container">
            <h1>Root: {number}</h1>
            <div id="grid">
                <Left1 number={number}></Left1>
                <Right1 onIncrease = {() => {setNubmer(number+1)}}></Right1>
            </div>
        </div>
    )
}
const Right1 = (props) => {
    return (
        <div>
            <h1>Right1</h1>
            <Right2 onIncrease={()=>{props.onIncrease()}}></Right2>
        </div>
    )
}
const Right2 = (props) => {
    return (
        <div>
            <h1>Right2</h1>
            <Right3 onIncrease={()=>{props.onIncrease()}}></Right3>
        </div>
    )
}
const Right3 = (props) => {
    return (
        <div>
            <h1>Right3</h1>
            <input type="button" value={"+"} onClick={() => {props.onIncrease()}}></input>
        </div>
    )
}
const Left1 = (props) => {
    return(
        <div>
            <h1>Left1: {props.number}</h1>
            <Left2 number={props.number}></Left2>
        </div>
    )
}

const Left2 = (props) => {
    return(
        <div>
            <h1>Left2: {props.number}</h1>
            <Left3 number={props.number}></Left3>
        </div>
    )
}

const Left3 = (props) => {
    return(
        <div>
            <h1>Left3: {props.number}</h1>
        </div>
    )
}

================================================================

2. Redux 설치
npm install redux react-redux

import {createStore} from "redux";
import { Provider, useSelector, useDispatch, connect } from "react-redux";

- 각각의 state의 변화를 불변하게 유지해야 함
--> 새로운 state를 만들 때 과거의 state를 복제하여 사용

- Provider:     state를 어떤 컴포넌트들에 제공할 지 가장 바깥쪽에 있는 울타리를 정하는 역할
                - props 중에 store을 반드시 정의해야 함
                --> Redux와 React를 연결하여 React 컴포넌트 트리에서 Redux 스토어를 사용할 수 있도록 하기 위함
- useSelector:  어떤 state 값을 쓰고 싶은지 선택
- useDispatch:  state 값을 변경할 때 사용

================================================================

3. Redux 사용

const reducer = (currentState, action) => {
    
    if(currentState === undefined){
        return {
            number: 1,                  // number의 기본값을 1로 지정
        };
    }
    const newState = {...currentState};
    if(action.type === "PLUS"){
        newState.number++;
    }
    return newState;
}
const store = createStore(reducer);


App()
<Provider store={store}>
    <Left1></Left1>
    <Right1></Right1>
</Provider>

Right3()
    const dispatch = useDispatch();
    
    return (
        <input type="button" value={"+"} onClick={() => {dispatch({type : "PLUS"})}}></input>
    )

Left3()
    const number = useSelector((state) => state.number);

    return(
        <h1>Left3: {number}</h1>
    )

    1. const reducer 및 const store 설정
    - const reducer: 현재 state 상태에 대한 설정
    - const store:  수정되면 안되는 store를 상수로 선언하고 reducer 주입
    2. state 갱신 설정
    - 리덕스는 각각의 state 변화를 불변하게 유지해야하기 때문에 기존 state를 복제해서 사용
    3. Provider store={store} 설정
    4. Left3의 useSelector 설정
    - reducer 설정할 때, state가 없는 상태일 때는 1이 부여되도록 기본값 설정됨
    --> state.number을 출력하는 함수를 통해서 상수 설정
    ==> 상수 출력
    5. action 설정
    - action.type이 plue면 신규 state 값 +1이 되도록 설정
    6. Right3의 useDispatch 설정
    - useDispatch()를 사용하는 상수 선언
    - 해당 상수에 값을 넣는 이벤트 선언

 

'단순 코드 기록 > RE: React' 카테고리의 다른 글

redux toolkit 기초  (0) 2024.05.23
Context Api 기초  (0) 2024.05.22
Styled Components 기초  (0) 2024.05.22
Router 기초  (0) 2024.05.21
React 기초  (0) 2024.05.20