React Redux Tutorials - 6 - Reducers
Reducer
// (1) define a default state
// state has to be represented by a single object.
const initialState = {
numOfCakes: 10
}
// initialState is passed in as an argument to the reducer function
// (2) define a reducer function
// (previousState, action) => newState
const reducer = (state = initialState, action) => {
switch(action.type) {
case BUY_CAKE: return {
numOfCakes: state.numOfCakes - 1
}
// ! we are not mutating the state object but return a new object.
// if there was an action which we haven't accounted for
default: return state
}
}
In reality, your state object might contain more than one property. That is why it is always safer to first create a copy of the state object and then change only the properties that need to.To make a copy of the state object, we use the spread operator (...state). We are asking the reducer to first make a copy of the state object and then only update the numOfCakes. If there were other properties they would remain unchanged.
const reducer = (state = initialState, action) => {
switch(action.type) {
case BUY_CAKE: return {
...state,
numOfCakes: state.numOfCakes - 1
}
default: return state
}
}
Reference
この問題について(React Redux Tutorials - 6 - Reducers), 我々は、より多くの情報をここで見つけました https://velog.io/@jheeju/React-Redux-Tutorials-6-Reducersテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol