An action is a plain JavaScript object that has a type field. You can think of an action as an event that describes something that happened in the application.
const addTodoAction = {
type: 'todos/todoAdded',
payload: 'Buy milk'
}
type
속성은 필수이고, 그 외는 자유롭게 작성할 수 있다.
An action creator is a function that creates and returns an action object. We typically use these so we don't have to write the action object by hand every time
const addTodo = text => {
return {
type: 'todos/todoAdded',
payload: text
}
}
액션을 생성해주는 함수로서, 나중에 컴포넌트에서 더욱 쉽게 액션을 발생시키기 위해 사용한다.
필수로 사용해야하는 것은 아니고 액션을 발생 시킬 때마다 직접 액션 객체를 작성할 수도 있다.
A reducer is a function that receives the current state
and an action
object, decides how to update the state if necessary, and returns the new state: (state, action) => newState
. You can think of a reducer as an event listener which handles events based on the received action (event) type.
const initialState = { value: 0 }
function counterReducer(state = initialState, action) {
// Check to see if the reducer cares about this action
if (action.type === 'counter/increment') {
// If so, make a copy of `state`
return {
...state,
// and update the copy with the new value
value: state.value + 1
}
}
// otherwise return the existing state unchanged
return state
}
리듀서는 변화를 일으키는 함수로서, state
와 action
을 파라미터로 받는다.
현재의 상태와 전달 받은 액션을 참고하여 새로운 상태를 만들어서 반환한다.
리덕스에서는 한 애플리케이션당 하나의 스토어를 만들게 된다.
store
안에는 state
와 reducer
들어가있고, 추가적으로 몇가지 내장 함수들이 있다.
The Redux store has a method called dispatch
. The only way to update the state is to call store.dispatch()
and pass in an action object. The store will run its reducer function and save the new state value inside, and we can call getState()
to retrieve the updated value.
You can think of dispatching actions as "triggering an event" in the application. Something happened, and we want the store to know about it. Reducers act like event listeners, and when they hear an action they are interested in, they update the state in response.
const increment = () => {
return {
type: 'counter/increment'
}
}
store.dispatch(increment())
console.log(store.getState())
// {value: 2}
디스패치는 스토어의 내장함수 중 하나로서, 액션을 발생 시키는 것 이라고 이해하면 된다.
. dispatch
라는 함수에는 액션을 파라미터로 전달한다.
구독 또한 스토어의 내장함수 중 하나로서, 함수 형태의 값을 파라미터로 받아옵니다.
subscribe 함수에 특정 함수를 전달해주면, 액션이 디스패치 되었을 때 마다 전달해준 함수가 호출된다.
리액트에서 리덕스를 사용하게 될 때 보통 이 함수를 직접 사용하는 일은 별로 없다.
그 대신에 react-redux 라는 라이브러리에서 제공하는 connect
함수 또는 useSelector
Hook 을 사용하여 리덕스 스토어의 상태에 구독합니다.
Selectors are functions that know how to extract specific pieces of information from a store state value.
As an application grows bigger, this can help avoid repeating logic as different parts of the app need to read the same data
const selectCounterValue = state => state.value
const currentValue = selectCounterValue(store.getState())
console.log(currentValue)
// 2
정보 출처
잘 읽었습니다. 좋은 정보 감사드립니다.