이 글은 [[한글자막] React 완벽 가이드 with Redux, Next.js, TypeScript]를 수강하며 정리한 글입니다.

 

 

⚛️ 기본 환경: IDE: VS code, Language: React

 

 

useEffect()

: 리액트 컴포넌트가 렌더링 될 때마다 특정 작업을 실행할 수 있도록 하는 Hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  useEffect(() => {
    fetchMoviesHandler();
  }, [fetchMoviesHandler]);
 
  async function fetchMoviesHandler() {
    setIsLoading(true);
    setError(null);
 
    try{
      const response = await fetch("https://swapi.dev/api/films/");
      
      if(!response.ok){
        throw new Error('Something went wrong!');
      }
 
      const data = await response.json();
  
      const transformedMovies = data.results.map(movieData => { // 필요한 데이터만 가져와서 key값을 변환
        return {
          id: movieData.episode_id,
          title: movieData.title,
          openingText: movieData.opening_crawl,
          releaseDate: movieData.release_date,
        };
      });
  
      setMovies(transformedMovies);
    } catch(error) {
      setError(error.message);
    }
    setIsLoading(false);
  };
 
 
 

🚨 상기 코드를 수행할 경우, useEffect 함수에서 fetchMoviesHandler 함수를 호출하면 컴포넌트가 렌더링될 때마다 fetchMoviesHandler 함수가 호출되어 무한 로딩이 발생

* fetchMoviesHandler: fetch()로 외부 데이터를 가져오며, 이 때, re-rendering됨

 

⭐ 대안: useCallBack() 사용

useCallBack()

:  첫 번째 인자로 넘어온 함수를, 두 번째 인자로 넘어온 배열 형태의 함수 실행 조건의 값이 변경될 때까지 저장해놓고 재사용할 수 있게하는 Hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  const fetchMoviesHandler = useCallback(async () => {
    setIsLoading(true);
    setError(null);
 
    try{
      const response = await fetch("https://swapi.dev/api/films/");
      
      if(!response.ok){
        throw new Error('Something went wrong!');
      }
 
      const data = await response.json();
  
      const transformedMovies = data.results.map(movieData => { // 필요한 데이터만 가져와서 key값을 변환
        return {
          id: movieData.episode_id,
          title: movieData.title,
          openingText: movieData.opening_crawl,
          releaseDate: movieData.release_date,
        };
      });
  
      setMovies(transformedMovies);
    } catch(error) {
      setError(error.message);
    }
    setIsLoading(false);
  }, []);
 
 
 

 

 

참고 자료

 

[React] 리액트 Hooks : useCallback() 함수 사용법

🚀 useCallback() useCallback은 useMemo와 비슷한 Hook입니다. useMemo는 특정 결괏값을 재사용할 때 사용하는 반면, useCallback은 특정 함수를 새로 만들지 않고 재사용하고 싶을 때 사용하는 함수입니다. useC

cocoon1787.tistory.com

 

⚛️ 기본 환경: IDE: VS code, Language: React

 

 

발생 Error

React에서 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useDispatch } from "react-redux";
import classes from "./CartItem.module.css";
import { cartActions } from "../../store/cart-slice";
 
const CartItem = (props) => {
  const dispatch = useDispatch();
  const { title, quantity, id, total, price } = props.item;
  
  const removeItemHandler = () => {
    dispatch(cartActions.removeItemToCart(id));
  };
  const addItemHandler = () => {
    dispatch(cartActions.addItemToCart(id, title, price));
  };
 
  return (
    <li className={classes.item}>
      <header>
        <h3>{title}</h3>
        <div className={classes.price}>
          ${total.toFixed(2)}{" "}
          <span className={classes.itemprice}>(${price.toFixed(2)}/item)</span>
        </div>
      </header>
      <div className={classes.details}>
        <div className={classes.quantity}>
          x <span>{quantity}</span>
        </div>
        <div className={classes.actions}>
          <button onClick={removeItemHandler}>-</button>
          <button onClick={addItemHandler}>+</button>
        </div>
      </div>
    </li>
  );
};
 
export default CartItem;
 
 
 

🚨 다음과 같은 오류 발생

TypeError: Cannot read properties of undefined (reading 'toFixed')

 

 

발생 원인

addItemToCart로 전달한 action.payload값이 객체가 아닌 개별값으로 전달

action.payload = id = newItem이 되어 state 업데이트가 제대로 일어나지 않음

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { createSlice } from "@reduxjs/toolkit";
 
const cartSlice = createSlice({
  name"cart",
  initialState: {
    items: [],
    totalQuantity: 0,
  },
  reducers: {
    addItemToCart(state, action) {
      const newItem = action.payload;
      const existingItem = state.items.find((item) => item.id === newItem.id);
      state.totalQuantity++;
      if (!existingItem) {
        state.items.push({
          id: newItem.id,
          price: newItem.price,
          quantity: 1,
          totalPrice: newItem.price,
          name: newItem.title,
        });
      } else {
        existingItem.quantity++;
        existingItem.totalPrice = existingItem.totalPrice + newItem.price;
      }
    },
    removeItemToCart(state, action) {
      const id = action.payload;
      const existingItem = state.items.find((item) => item.id === id);
      state.totalQuantity--;
      if (existingItem.quantity === 1) {
        state.items = state.items.filter((item) => item.id !== id);
      } else {
        existingItem.quantity--;
        existingItem.totalPrice = existingItem.totalPrice - existingItem.price;
      }
    },
  },
});
 
export const cartActions = cartSlice.actions;
 
export default cartSlice;
 
 

 

 

해결 방법

{id, title, price}를 객체로 묶어서 전달

action.payload = {id, title, price} = newItem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useDispatch } from "react-redux";
import classes from "./CartItem.module.css";
import { cartActions } from "../../store/cart-slice";
 
const CartItem = (props) => {
  const dispatch = useDispatch();
  const { title, quantity, id, total, price } = props.item;
  
  const removeItemHandler = () => {
    dispatch(cartActions.removeItemToCart(id));
  };
  const addItemHandler = () => {
    dispatch(cartActions.addItemToCart({id, title, price}));
  };
 
  return (
    <li className={classes.item}>
      <header>
        <h3>{title}</h3>
        <div className={classes.price}>
          ${total.toFixed(2)}{" "}
          <span className={classes.itemprice}>(${price.toFixed(2)}/item)</span>
        </div>
      </header>
      <div className={classes.details}>
        <div className={classes.quantity}>
          x <span>{quantity}</span>
        </div>
        <div className={classes.actions}>
          <button onClick={removeItemHandler}>-</button>
          <button onClick={addItemHandler}>+</button>
        </div>
      </div>
    </li>
  );
};
 
export default CartItem;
 
 
 

 

 

참고 자료

⭐ Web Browser에서 Debugging하는 법

 

이 글은 코딩알려주는누나의 [리액트 초보자 입문강의 3탄]를 수강하며 정리한 글입니다.

 

 

⚛️ 기본 환경: IDE: replit, Language: React

* replit: Browser 기반 IDE

 

 

🚨 화면단에 보여지는 요소들을 매번 업데이트할 경우, 비용과 시간이 많이 발생하는 문제를 해결하기 위해 variable 대신 state 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, {useState} from 'react';
 
import './App.css'
 
export default function App() {
  let count1 = 0;
  const [count2, setCount2] = useState(0);
  const increase = () => {
   count1 += 1;
    setCount2(count2 + 1);
    console.log('count1: ' + count1 + ', count2: ' + count2);
  }
  
  return (
    <main>
      <div>variable: {count1}</div>
      <div>state: {count2}</div>
      <button onClick={increase}>증가</button>
    </main>
  )
}
 
 
 

⭐ state는 변수와 달리 변경 시, state에 값을 직접 대입하는 것이 아닌 set 함수를 활용

React에서는 variable과 state를 구분하여 state가 업데이트 될 때만 UI(User Inferface, 사용자가 제품/서비스를 사용할 때, 마주하게 되는 면)를 업데이트

 

해당 동작에 대한 console.log를 살펴보면 다음과 같음

🚨variable-count1은 value가 1로 고정되며 state-count2는 UI보다 value가 1이 작음

useState() 사용 시, state값이 변경될 경우 해당 컴포넌트(App function)를 새로고침하여 변수값이 0으로 초기화되어 버튼 클릭시 초기값 0에 1을 더해주게 됨 → 변수의 값이 기억되지 않으므로 임시 저장용으로만 사용

useState()에서 set 메서드는 비동기적으로 작동 = UI를 업데이트하는 set 함수의 모든 동작을 모아서 한 번에 처리

console에 반환되는 값은 업데이트가 진행되기 전(set 함수가 동작하기 )의 값으로 반환이 되고, UI는 모든 set 함수가 한 번에 처리되어 업데이트 된 state 값을 전달받게 됨

1
2
3
4
5
6
  const increase = () => {
    count += 1;
    setCount2(count2 + 1);
    console.log('count1: ' + count1 + ', count2: ' + count2);
  }
 
 
 

increase 메서드 호출 시,

1. count1 업데이트

2. setCount2 대기

3. console.log 실행

4. 해당 컴포넌트 내 모든 set 함수 실행

5. UI 업데이트

 

🟨 기본 환경: IDE: VS code, Language: JavaScript

 

 

발생 Error

CMD에서 node productSlice.js로 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const { createSlice } = require('@reduxjs/toolkit');
// createSlice: reducer 생성, 매개변수-객체
 
let initialState = {
    productList: [],
    selectedItem: null,
};
 
// name: unique한 action name을 만드는데 쓰이는 prefix
// initialState: reducer state
// reducers: state, action을 매개변수로 받는 함수 생성
const productSlice = createSlice({
    name'product',
    initialState,
    reducers: {
        getAllProduct(state, action) {
            state.productList= action.payload.data
            // initialState의 productList을 action의 payload.data로 변경
        },
        getSingleProduct(state, action) {
            state.selectedItem = action.payload.data
        },
    }
});
 
console.log('ppp', productSlice);
 
export default productSlice.reducer;
// productSlice: reducers가 담긴 reducer 반환
 
 
 

🚨 다음과 같은 Error 발생

Error: Cannot find module 'C:\Users\user\Desktop\REACT\redux\productReducer.js'

 

 

발생 원인

*.js 파일이 존재하는 올바른 위치가 아닌 곳에서 파일을 실행시키고자 함

 

 

해결 방법

*.js 파일이 존재하는 위치로 이동 후 node 파일명.js 후 실행

 

🟨 기본 환경: IDE: VS code, Language: JavaScript

 

 

발생 Error

CMD에서 node productSlice.js로 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import {createSlice} from '@reduxjs/toolkit';
// createSlice: reducer 생성, 매개변수-객체
 
let initialState = {
    productList: [],
    selectedItem: null,
};
 
// name: unique한 action name을 만드는데 쓰이는 prefix
// initialState: reducer state
// reducers: state, action을 매개변수로 받는 함수 생성
const productSlice = createSlice({
    name'product',
    initialState,
    reducers: {
        getAllProduct(state, action) {
            state.productList= action.payload.data
            // initialState의 productList을 action의 payload.data로 변경
        },
        getSingleProduct(state, action) {
            state.selectedItem = action.payload.data
        },
    }
});
 
console.log('ppp', productSlice);
 
export default productSlice.reducer;
// productSlice: reducers가 담긴 reducer 반환
 
 
 

🚨 다음과 같은 Error 발생

SyntaxError: Cannot use import statement outside a module

 

 

발생 원인

Node.js에서 파일에서 import 문을 사용하려고 했을 때 발생

 

 

해결 방법

Node.js에서는 import 대신 require 문을 사용하여 모듈을 가져와야 함

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const { createSlice } = require('@reduxjs/toolkit');
// createSlice: reducer 생성, 매개변수-객체
 
let initialState = {
    productList: [],
    selectedItem: null,
};
 
// name: unique한 action name을 만드는데 쓰이는 prefix
// initialState: reducer state
// reducers: state, action을 매개변수로 받는 함수 생성
const productSlice = createSlice({
    name'product',
    initialState,
    reducers: {
        getAllProduct(state, action) {
            state.productList= action.payload.data
            // initialState의 productList을 action의 payload.data로 변경
        },
        getSingleProduct(state, action) {
            state.selectedItem = action.payload.data
        },
    }
});
 
console.log('ppp', productSlice);
 
export default productSlice.reducer;
// productSlice: reducers가 담긴 reducer 반환