본문 바로가기
Java, JavaScript/React-Native

combineReducers

by swconsulting swconsulting 2018. 7. 11.



reducers/todos.js

export default function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text])
default:
return state
}
}

reducers/counter.js

export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}

reducers/index.js

import { combineReducers } from 'redux'
import todos from './todos'
import counter from './counter'
export default combineReducers({
todos,
counter
})

App.js

import { createStore } from 'redux'
import reducer from './reducers/index'
const store = createStore(reducer)
console.log(store.getState())
// {
// counter: 0,
// todos: []
// }
store.dispatch({
type: 'ADD_TODO',
text: 'Use Redux'
})
console.log(store.getState())
// {
// counter: 0,
// todos: [ 'Use Redux' ]
// }

Tips

  • This helper is just a convenience! You can write your own combineReducers that works differently, or even assemble the state object from the child reducers manually and write a root reducing function explicitly, like you would write any other function.

  • You may call combineReducers at any level of the reducer hierarchy. It doesn't have to happen at the top. In fact you may use it again to split the child reducers that get too complicated into independent grandchildren, and so on.

Source : https://redux.js.org/api-reference/combinereducers

'Java, JavaScript > React-Native' 카테고리의 다른 글

Font Size Control.  (0) 2018.07.15
Hide Header in React Native  (0) 2018.07.14
combineReducers  (0) 2018.07.11
PropTypes can no longer be required from react  (0) 2018.07.10
Unable to use 'react-native-init {project}'  (0) 2018.07.09
How to count length of JSON array element?  (0) 2018.07.06

댓글0