redux

1.combineReducers (reducers)

The role of the combineReducers auxiliary function is to combine an object with multiple different reducer functions as the value into a final reducer function, and then you can call createStore on this reducer.

The merged reducer can call individual child reducers and merge their results into a single state object. The structure of the state object is determined by the keys of multiple reducers passed in.

Ultimately, the structure of the state object will look like this:

{
  reducer1: ...
  reducer2: ...
}

Control the naming of the state key by naming the reducer of the incoming object differently. For example, you can call combineReducers({ todos: myTodosReducer, counter: myCounterReducer }) to change the state structure to { todos, counter }.

It's common practice to name reducers and then state to split that information, so you can use the ES6 shorthand: combineReducers({ counter, todos }). This is the same as combineReducers({ counter: counter, todos: todos }) .

parameter

reducers (Object): An object whose value corresponds to different reducer functions, which will be merged into one later. The following will introduce the rules that the incoming reducer function needs to meet.

return value

(Function): A reducer that calls all reducers in the reducers object and constructs a state object with the same structure as the reducers object.

Example:

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 all from './all'
import counter from './counter'

export default combineReducers({
  everyone,
  counter
})

App.js

import { createStore } from 'redux'
import reducer from './reducers/index'

let store = createStore(reducer)
console.log(store.getState())
// {
//   counter: 0,
// everyone: []
// }

store.dispatch({
  type: 'ADD_TODO',
  text: 'Use Redux'
})
console.log(store.getState())
// {
//   counter: 0,
//   todos: [ 'Use Redux' ]
// }

Tips

(1) This method only plays an auxiliary role! You can implement combineReducers with different functions by yourself, or even write a root reducer function explicitly like other functions, and use it to manually assemble child reducers into state objects.

(2) CombineReducers can be called at any level of the reducer hierarchy. It doesn't have to be the outermost layer. In fact, you can split some complex child reducers into separate grandchild reducers, or even more layers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325163244&siteId=291194637