Redux Counter1

๋ฐ•์„œํ˜„ยท2023๋…„ 8์›” 30์ผ
0
post-thumbnail

๐Ÿ“ redux / moduls / counter.js

// ์ดˆ๊ธฐ ์ƒํƒœ(state)
const initialState = {
  number: 0
}
//const [number, setNumber] = useState(0)

// ๋ฆฌ๋“€์„œ : ํ•จ์ˆ˜
// input : state์™€ action
const counter = (state=initialState, action) => {
  switch (action.type) {
    default:
      return state
  }
}

export default counter
  • action์˜ ํƒ€์ž…์— ๋”ฐ๋ผ ์ž‘์—…์„ ์ˆ˜ํ–‰ ํ•  ๊ฒƒ์ด๋‹ค.
  • ๋ฆฌ๋“€์„œ : 'state์— ๋ณ€ํ™”๋ฅผ ์ผ์œผํ‚ค๋Š”' ํ•จ์ˆ˜
    • (1) state ๋ฅผ action์˜ type์— ๋”ฐ๋ผ ๋ณ€๊ฒฝํ•˜๋Š” ํ•จ์ˆ˜

๐Ÿ“ redux / moduls / users.js

// ์ดˆ๊ธฐ ์ƒํƒœ(state)
const initialState = {
  userId: 123
}

// input : state์™€ action
const users = (state=initialState, action) => {
  switch (action.type) {
    default:
      return state
  }
}

export default users

๐Ÿ“ redux / config / configStore.js

// ์ค‘์•™ ๋ฐ์ดํ„ฐ ๊ด€๋ฆฌ์†Œ(store)๋ฅผ ์„ค์ •ํ•˜๋Š” ๋ถ€๋ถ„
import { combineReducers, createStore } from "redux";
import counter from "../moduls/counter";
import users from "../moduls/users";

const rootReducer = combineReducers({
  counter, users
})
const store = createStore(rootReducer)

export default store
  • counter ์ž„ํฌํŠธ

๐Ÿ“ App.jsx

import React from 'react'
import { useSelector } from 'react-redux'

function App() {

  // ์—ฌ๊ธฐ์—์„œ store์— ์ ‘๊ทผํ•˜์—ฌ, counter์˜ ๊ฐ’์„ ์ฝ์–ด์˜ค๊ณ  ์‹ถ๋‹ค
  // useSelector
  // ๋งค๊ฐœ๋ณ€์ˆ˜์˜ state๋Š” ์ค‘์•™์ €์žฅ์†Œ ์•ˆ์— ์žˆ๋Š” state ์ „์ฒด๋ฅผ ๋งํ•œ๋‹ค.
  const data = useSelector((state) => {
    return state;
  })

  console.log(data)
  return (
    <div>App</div>
  )
}

export default App

  • ๋งŒ์•ฝ counter๋งŒ ๊ฐ€์ง€๊ณ  ์˜ค๊ณ  ์‹ถ๋‹ค๋ฉด App.jsx์—์„œ
const data = useSelector((state) => {
  return state;
})
const counter = useSelector((state) => {
  return state.counter;
})

console.log(counter.number)
  • state -> state.counter ์ด๋ ‡๊ฒŒ ๋ฐ”๊พธ๋ฉด ๋จ.

0๊ฐœ์˜ ๋Œ“๊ธ€