Day-5-Starting-Point
🤷🏾♂️
Flux와는 비슷하면서도 조금 다른 개념
지금 우리가 만든 Component의 구조는
API 요청도 많았고
Lifecycle Hook도 많이 사용했고
Method도 많이 만들어 사용했고
최대한 한 군데 모아놓고 Component들은 필요한 props만 받아서 쓰는 것 🙌🏽
State
View: this.render
Store: this.state
Action: this.handleChange
Dispatcher: this.setState
const state = [
'React 복습',
'수업내용 정리',
'밥 먹기',
]
const reducer = (state, action) => {
if (action.type === ADD_TODO_LIST_ITEM) {
return {
...state,
action.item,
}
}
}
nextState = reducer(state, { type: ADD_TODO_LIST_ITEM, data: '영화보기'})reducer()는?
Event 발생
=>
Handler 호출
=>
this.setState()
=>
this.render()
Event발생(액션 발생)
=>
Handler 호출(액션 Dispatch)
=>
reducer()
=>
관련 컴포넌트들 this.render
버튼 클릭 => Action 발생
state
nextState
action = { type: 'CLICK', payload: '...' }
store.dispatch(action)
reducer(state, action)
store
store에서 사용하는 method
getState()
dispatch()
프로덕트를 만들 수 있다
좋은 프로턱트를 만들 수 있다
OX Quiz:
actionCreator는 한 종류의 action만 만들어야한다
nextState = reducer(currentState, action) => {
if (action.type === 'ACTION_ONE') {
return { ...state }
}
return { ...state }
}
reducer(currentState, action) => nextState
syncAction😏 => syncAction😏 => syncAction😏 => asyncAction😲=> syncAction😏
const asyncActionCreator = (param) => {
return (dispatch) => {
dispatch() // 어떤 액션?
return fetch(param.URL)
.then((resp) => resp.json())
.then((responseData) => {
dispatch(action); // 어떤 액션?
})
.catch((error) => {
dispatch() // 어떤 액션?
})
}
}Hint: WordLists 컴포넌트에서의 예외 케이스들
Error, isLoading
const store = {
isLoading: false,
wordLists: [],
selectedWordList: {id: 4, title: 'abc', ...},
}
const fetchWordsFromWordListId = (id) => {
return (dispatch) => {
dispatch({ type: 'IS_LOADING' })
fetch(generateURL(id))
.then()
.then(() => dispatch({ type: 'SUCCESS'}))
.catch(() => dispatch({ type: 'FAIL'}))
}
}
최소한의 API 요청
const store = {
isLoading: false,
wordLists: [],
selectedWordList: {id: 4, title: 'abc', ...},
cachedWordList: [],
}
const fetchWordsFromWordListId = (id) => {
return (dispatch) => {
if (id is in cachedWordList) {
return dispatch({ type: 'SUCCESS'})
} else {
dispatch({ type: 'IS_LOADING' })
fetch(generateURL(id))
.then()
.then(() => dispatch({ type: 'SUCCESS'}))
.catch(() => dispatch({ type: 'FAIL'}))
}
}
}