라벨이 리엑트인 게시물 표시

React - Reducer

이미지
  버전정보 react : ^18.2.0 이전글 : React - Context 1. react 설치 - terminal을 이용하여 react를 설치합니다. (node v20.10.0) $ npx create-react-app [project name] copy 사진1) Reducer 개념도 이전 글에서 context만으로 state를 변경 했습니다. 하지만 이때 다른 컴포넌트에서 잘못된 값을 업데이트 하게 된다면 모든 components가 영향을 받게 됩니다. 사진1의 번호순으로 설명을 하도록 하겠습니다. 1번 : component가 state의 value를 변경하기 위해서 Dispatch에 요청을 합니다. 이때 action을 인자로 주는데 type와 payload(선택적)를 입력합니다. 2번 : dispatch에서 component에서 받은 action을 Reducer에 전달을 합니다. 3번 : Reducer에서 dispatch에 받은 action의 type을 확인합니다. 해당 type과 일치하면 지정된 state 변경을 진행합니다. 이때 payload를 받으면 해당 payload를 이용하여 state를 변경합니다. 4번 : state가 변경되었다. 해당 state를 사용하는 모든 component를 re-randering한다. 기존 Context와 다른점은 이제 Component에서 state 값의 변경을 할려면 Dispatch을 통해서 간접적으로 변경이 가능하다는 것입니다. GitHub Link :  https://github.com/Alex-Choi0/react_context_reducer_sample1.git

React - Context

이미지
  버전정보 react : ^18.2.0 1. react 설치 - terminal을 이용하여 react를 설치합니다. (node v20.10.0) $ npx create-react-app [project name] copy 사진1) react를 npx으로 셋팅 사진2) context 추상도 context가 커버하는 범위에 따라 그에 영향받는 components들이 있습니다. 사진2에서 Context가 App전체에 영향을 준다면 components가 App의 하위에 존재하는한 어디든지 state값을 사용할수 있습니다. 사진3) context value 업데이트 예로 들어 A component에서 method를 이용해서 Context의 value값을 변경했습니다. 이때 state는 변경과 동시에 적용이 됩니다. 사진4) context 업데이트시 다른곳도 적용 적용된 value를 사용하는 다른 component(A, B)에 변화에 따른 re-randering이 들어갑니다.  // src/context/count.context.jsx import { createContext , useState } from "react" // 실제 컴포넌트에서 Access할 데이터 export const CountContext = createContext ({ currentNum : null , // 실제 컴포넌트에서 읽을 카운트값 setCurrentNum : () => null , // 카운트 값을 변경하기 위한 메소드 }) export const CountProvider = ({ children }) => { // useState를 이용하여 currentNum, setCurrentNum을 설정하고 currentNum의 초기값을 0으로 한다 const [ currentNum , setCurrentNum ] = useState ( 0 ) // Provider를 이용하여 해당...

React-Redux_기초6 객체를 Redux store에 저장하기

이미지
지금까지는 react-redux store에 숫자로만 조작을 하였지만 이번에는 데이터, 즉 객체 데이터를 넣도록 하겠습니다.  먼저 저번과 마찬가지로 Action, Reducer, Types 3개를 resume 폴더안에 말들어줍니다. export const ADD_RESUME = "ADD_RESUME" ; // 이력서를 지원하기 위한 타입 입력 먼저 resumeTypes.js에 위 코드를 작성해 줍니다. import { ADD_RESUME } from './resumeTypes' ; export const addResume = ( resume = { Name : '' , Email : '' }) => { return { type : ADD_RESUME , payload : resume } } 이제 액션부분을 resumeAction.js부분에 코딩을 해줍니다. 여기서 cookie파트와 비슷하면서 다른점이 있습니다. 인자를 받지만 이번에는 객채를 받습니다. 키값이 Name, Email로 구성된 객체를 받습니다. 이것은 payload에 전달되서 reducer에 보내기게 됩니다. // resumeTypes에서 이력서 지원 타입을 받아온다. import { ADD_RESUME } from './resumeTypes' ; // 지원자의 이름과 이메일을 state로 저장한다 const initialState = { resume : { Name : '' , Email : '' } // 초기 이력서는 빈공간 }; // cookieReducer는 이전 toyReducer와 달리 payload에 따라 수량이 변화한다. const resumeReducer = ( state = initialState , action ) => ...

React-Redux_기초5 새로운 component생성하고 React실행

이미지
import { React , useState } from 'react' ; import { connect } from 'react-redux' ; // react, redux연결 import { buyCookie , sellCookie } from '../Redux' ; // toy action 연결 // 위 함수는 App.js에 추가할 component function CookiePart ( props ){ // number의 변수를 바꾸기 위한 useState사용 const [ number , setNumber ] = useState ( 1 ); console . log ( 'Cookie(props) : ' , typeof props , props ); console . log ( 'Cookie(props.numberOfCookie) : ' , typeof props . numOfCookie , props . numOfCookie ); // return할 component return ( < div > < h2 > Number of Cookies - { props . numOfCookie } </ h2 > { /* input에 숫자를 입력하여 사고팔때의 쿠기수량을 조절합니다. */ } < input type = 'text' value = { number } onChange = { e => setNumber ( e . target . value ) } /> < button onClick = { () => props . buyCookie ( number ) } > Buy { number } Cookies </...

React-Redux_기초4 새로운 Reducer 생성하기

이미지
이번에는 Cookie를 판매하는 파트를 Redux를 이용하여 만들도록 하겠습니다.    일단 위의 폴더에서 CookiePart.js component와 cookie폴더가 추가 되었습니다. 2개의 component는 구조가 비슷하지만 toy와 달리 CookiePart component는 구입, 판매 수량을 조절할수 있습니다. 이제 toy폴더와 같이 3개의 js파일(cookieAction.js, cookieReducer.js, cookieTypes.js)을 생성합니다.  export const BUY_COOKIE = "BUY_COOKIE" ; // 쿠기를 사기위한 타입 입력 export const SELL_COOKIE = "SELL_COOKIE" ; // 쿠기를 팔기위한 타입 입력 cookieType.js파일을 위와같이 코딩해 줍니다. import { BUY_COOKIE , SELL_COOKIE } from './cookieTypes' ; export const buyCookie = ( num = 1 ) => { return { type : BUY_COOKIE , payload : num } } export const sellCookie = ( num = 1 ) => { return { type : SELL_COOKIE , payload : num } } 이제 cookieAction.js 부분도 위와같이 코딩을 해줍니다. 다만 이전 toyAction.js와 다른점은 함수인자가 추가된 것입니다. cookie부분은 사용자가 판매, 구매 수량을 조절할수 있게 하기 위해서 num인자를 추가했습니다. 하지만 인자가 추가되지 않는 상황을 대비하여 숫자가 들어오지 않을시 default value를 1로합니다.  // cookieTypes에서 구매와 판매 타입을 받아온다. impor...

React-Redux_기초3 components폴더 및 App.js 코딩

이미지
 저번 글과 마찬가지로 Redux에 대한 코딩을 진행하겠습니다.  이제 components폴더 안에 ToyPart.js를 생성한다. 이것은 React의 components이다.  import React from 'react' ; import { connect } from 'react-redux' ; // react, redux연결 import { buyToy , sellToy } from '../Redux' ; // toy action 연결 // 위 함수는 App.js에 추가할 component function ToyPart ( props ){ // return할 component return ( < div > < h2 > Number of Toys - { props . numOfToys } </ h2 > < button onClick = { props . buyToy } > Buy Toys </ button > < button onClick = { props . sellToy } > Sell Toys </ button > </ div > ) } // Redux실행시 현재 state에 저장된 기록을 불러옵니다. const mapStateToProps = ( state ) => { console . log ( 'mapStateToProps : ' , state ); return { numOfToys : state , } } // Redux실행시 각 action에 따른 method를 Arrow function에따라 dispatch합니다. const mapDispatchToProps = ( dispatch ) => { ...

React-Redux_기초2 Redux 폴더 코딩

이미지
 이제 React안에 Redux를 사용할수 있도록 코딩하도록 하겠습니다.  위 사진과 같이 Redux폴더 안에 toy라는 폴더를 생성하고 3개의 파일을 만듭니다. 이전에 작성한 글처럼 toy에 관련된 Types, Action, Reducer를 이용합니다. export const BUY_TOY = "BUY_TOY" ; // 장난감을 사기위한 타입 입력 export const SELL_TOY = "SELL_TOY" ; // 장난감을 팔기위한 타입 입력 toyTypes.js은 BUY_TOY, SELL_TOY에 문자열을 변수로 입력하고 export합니다. import { BUY_TOY , SELL_TOY } from './toyTypes' ; // 장난감을 사기위한 액션 export const buyToy = () => { return { type : BUY_TOY }; }; // 장난감을 팔기위한 액션 export const sellToy = () => { return { type : SELL_TOY }; }; toyAction.js에는 toyTypes.js에서 BUY_TOY, SELL_TOY를  import해서 액션에 사용합니다. 액션은 2가지 buyToy, sellToy로 이루어 집니다.  import { BUY_TOY , SELL_TOY } from './toyTypes' ; // toyTypes에서 구매와 판매 타입을 받아온다. const initialState = { numOfToys : 20 // 초기 장난감 진열 갯수는 20개 }; const toyReducer = ( state = initialState , action ) => { switch ( action . type ){ case BUY_TOY : // 가게에서 ...