π https://github.com/happypoulp/redux-tutorial/wiki
Tutorial 06 - dispatch action
μ°λ¦¬λ μ§κΈκΉμ§ 리λμλ₯Ό λ§λ€μ΄ 보μκ³ μμ§ μ‘μ μ dispatch ν΄λ³΄μ§ μμλ€. μ΄μ νν 리μΌμμ μΌλ κ°μ 리λμλ‘ λͺκ°μ§ μ‘μ λ€μ λ€λ£¨μ΄λ³΄μ.
var userReducer = function (state = {}, action) {
console.log('userReducer μ΄ μ λ¬λ°μ μν', state, 'μ μ‘μ
', action)
switch (action.type) {
case 'SET_NAME':
return {
...state,
name: action.name
}
default:
return state;
}
}
var itemsReducer = function (state = [], action) {
console.log('itemsReducer μ΄ μ λ¬λ°μ μν', state, 'μ μ‘μ
', action)
switch (action.type) {
case 'ADD_ITEM':
return [
...state,
action.item
]
default:
return state;
}
}
import { createStore, combineReducers } from 'redux'
var reducer = combineReducers({
user: userReducer,
items: itemsReducer
})
var store_0 = createStore(reducer)
console.log("\n", '### It starts here')
console.log('μ΄κΈ°ν μ΄ν store_0 μ μν:', store_0.getState())
// Output:
// μ΄κΈ°ν μ΄ν store_0 μ μν: { user: {}, items: [] }
첫λ²μ§Έ μ‘μ μ dispatch ν΄λ³΄μβ¦ 01_simple-action-creator.md μμ λ§νλλλ‘ βactionμ dispatch νκΈ°μν΄μλβ¦ dispatch ν¨μκ° νμνλ€.β
μ°λ¦¬κ° μ°Ύκ³ μλ dispatch ν¨μλ Reduxκ° μ 곡νκ³ λͺ¨λ reducerλ€μ μ‘μ μ 보λΌκ±°λ€! dispatch ν¨μλ Redux μΈμ€ν΄νΈ μμ± βdispatchβλ‘ μ κ·Όκ°λ₯νλ€.
μ‘μ μ dispatch νκΈ°μν΄μ , κ°λ¨ν νΈμΆνλ©΄λλ€
store_0.dispatch({
type: 'AN_ACTION'
})
// Output:
// userReducer μ΄ μ λ¬λ°μ μν {} μ μ‘μ
{ type: 'AN_ACTION' }
// itemsReducer μ΄ μ λ¬λ°μ μν [] μ μ‘μ
{ type: 'AN_ACTION' }
κ° λ¦¬λμκ° ν¨μ¨μ μΌλ‘ νΈμ΄λμμ§λ§ μ΄ μ‘μ νμ μ λ°λ 리λμλ μκΈ°λλ¬Έμ μνλ λ³κ²½λμ§ μμλ€.
console.log('AN_ACTION μ‘μ
μ΄ν store_0 μν:', store_0.getState())
// Output: AN_ACTION μ‘μ
μ΄ν store_0 μν: { user: {}, items: [] }
κ·Έλ°λ° μ κΉ! μ‘μ μ 보λ΄κΈ° μν΄ action creatorλ₯Ό μ¬μ©νλ€κ³ νμλ€. actionCreatorλ₯Ό μ¬μ©ν μ μμ§λ§ κ·Έκ²μ μ‘μ μ 리ν΄νλκ² μ λΆμ΄κΈ° λλ¬Έμ μ΄ μμ μ λ€λ₯Έ 무μΈκ°λ₯Ό λ ν΄μ£Όμ§λͺ»νλ€. κ·Έλ μ§λ§ λμ€μμμ μ΄λ €μμ λκΈ°μν΄ flux μ΄λ‘ μ λ°λ₯Έ μ¬λ°λ₯Έ λ°©λ²μΌλ‘ ν΄λ³΄μ. κ·Έλ¦¬κ³ μ΄ action creatorλ₯Ό λ§λ€μ΄μ μ€μ λ‘ μ‘μ μ 보λ΄λ³΄μ.
var setNameActionCreator = function (name) {
return {
type: 'SET_NAME',
name: name
}
}
store_0.dispatch(setNameActionCreator('bob'))
// Output:
// userReducer μ΄ μ λ¬λ°μ μν {} μ μ‘μ
{ type: 'SET_NAME', name: 'bob' }
// itemsReducer μ΄ μ λ¬λ°μ μν [] μ μ‘μ
{ type: 'SET_NAME', name: 'bob' }
console.log('SET_NAME μ‘μ
μ΄ν store_0 μν:', store_0.getState())
// Output:
// SET_NAME μ‘μ
μ΄ν store_0 μν: { user: { name: 'bob' }, items: [] }
μ°λ¦¬λ 첫λ²μ§Έ μ‘μ μ λ€λ£¨μ΄ 보μκ³ μ°λ¦¬ μ΄ν리μΌμ΄μ μ μνλ₯Ό λ³κ²½μμΌ°λ€.
κ·ΈμΉλ§ μ΄κ±΄ λ무 κ°λ¨νκ³ μ€μ μ¬μ©μμ λ‘ μΆ©λΆνμ§ μλ€. μλ₯Ό λ€μ΄, μ‘μ μ dispatch νκΈ° μ μ action creator μμ λΉλκΈ° μμ μ νλ€λ©΄? μ΄κ²μ λ€μ νν 리μΌμμ μκΈ°ν΄ λ³Ό κ²μ΄λ€.
μ¬κΈ°κΉμ§κ° μ°λ¦¬ μ΄ν리μΌμ΄μ μ νλ¦μ΄λ€. ActionCreator -> Action -> dispatcher -> reducer
λ€μ: 07_dispatch-async-action-1.md