๐ŸคRedux - Part 2. React + Redux (2)

1. Store, ๊ฐ€๊ฒŒ ์ฐจ๋ฆฌ๊ธฐ

์ข€ ์•„๊นŒ handleSubmit ๋‚ด์˜ DOM ์š”์†Œ๋“ค์„ ์ฃผ์„์ฒ˜๋ฆฌํ•˜๊ณ  store.js ๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค.

ํ”„๋กœ์ ํŠธ ๊ฒฝ๋กœ ๋‚ด src ๋””๋ ‰ํ† ๋ฆฌ ์ƒ๋‹จ์—์„œ ์ƒ์„ฑํ–ˆ๋‹ค.

2. store.js ์ฝ”๋“œ

import { createStore } from 'redux'

const ADD = 'ADD'
const DELETE = 'DELETE'

export const addToDo = text => {
  return {
    type: ADD,
    text,
  }
}

export const deleteToDo = id => {
  return {
    type: DELETE,
    id,
  }
}

const reducer = (state = [], action) => {
  switch (action.type) {
    case ADD:
      return [...state, { text: action.text, id: Date.now() }]
    case DELETE:
      return state.filter(toDo => toDo.id !== action.id)
    default:
      return state
  }
}

const store = createStore(reducer)

export default store

๊ทธ๋Ÿฐ๋ฐ store.subscribe() ๋Š” ์–ด๋””๋กœ?

state ์— ๋ณ€ํ™”๊ฐ€ ์ƒ๊ธธ ๋•Œ๋งˆ๋‹ค App ์„ ๋ฆฌ๋ Œ๋” ํ•˜๊ฒŒ๋” ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ์•Œ๋ ค์คฌ๋˜ ์•„์ด๊ฐ€ subscribe ์ด๋‹ค.

๊ทธ๋ ‡๊ฒŒ ํ•˜๋ ค๋ฉด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์•ผ ํ•˜๋Š”๋ฐ, ์–ด์ œ ์ง„ํ–‰ํ–ˆ๋˜ Vanilla.js-Redux ์™€ ๋‹ฌ๋ฆฌ

React-Redux ๋Š” store ์˜ ๋ณ€๋™์‚ฌํ•ญ์— ๋Œ€ํ•ด subscribe ํ•˜๋Š” ๋ฐฉ์‹์ด ๋‹ค๋ฅด๋‹ค.

3. index.js ๊ทธ๋ฆฌ๊ณ  Provider

ํ˜„์žฌ App ์„ ๋ฐฉ๊ธˆ ๋งŒ๋“  store ์™€ ์—ฐ๊ฒฐํ•˜๋Š” ์ž‘์—…์„ ํ•˜๊ฒŒ ๋œ๋‹ค.

import { Provider } from 'react-redux'
import store from './store'

์•„.. store ๋Š” ์—ฌ๊ธฐ์„œ ๋ถˆ๋Ÿฌ์˜ฌ๋ ค๊ณ  exports default store ๋ฅผ ์„ ์–ธํ–ˆ๊ตฌ๋‚˜?!

์ด์ œ ReactDOM ๋‚ด ์ฝ”๋“œ๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ์ˆ˜์ •ํ–ˆ๋‹ค.

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

App ๊ณผ store ๋ฅผ ์—ฐ๊ฒฐํ•˜๊ธฐ ์œ„ํ•œ ๋‘ ๋ฒˆ์งธ๋Š” < App/ > ์„ Provider ๋กœ ๊ฐ์‹ธ์ฃผ๋Š” ๊ฒƒ์ด๋‹ค.

์„ธ ๋ฒˆ์งธ๋กœ๋Š” Provider ๋Š” store ๊ฐ€ ํ•„์š”ํ•ด์„œ props ๋กœ ์•„๊นŒ ๋งŒ๋“  store ๋ฅผ ๋‚ด๋ ค ์ฃผ์—ˆ๋‹ค.

index.js ์— Provider ๋ฅผ ๋ถˆ๋Ÿฌ์™€ ๋‚ด ์•ฑ์„ ์—ฐ๊ฒฐํ•จ์œผ๋กœ์จ ์–ป๋Š” ์ด์ ์ด ๋ฌด์—‡์ด ์žˆ์„๊นŒ?


Written by@[DotoriMook]
ํ”„๋ก ํŠธ์—”๋“œ ์ฃผ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž ๋„ํ† ๋ฆฌ๋ฌต์˜ ๊ธฐ์ˆ ๊ฐœ๋ฐœ ๋ธ”๋กœ๊ทธ ์ž…๋‹ˆ๋‹ค.

GitHubMediumTwitterFacebook