Redux sees a different state from Reducer

Imagine an interface with two React components:

<FilterContainer />

<UserListContainer />

We pull out an array of users from the server:

[
  {
    name: 'John',
    enjoys: ['Sailing', 'Running']
  },
  {
    name: 'Bob',
    enjoys: ['Running', 'Eating']
  },
  {
    name: 'Frank',
    enjoys: ['Sailing', 'Eating']
  }
]

The user interface looks something like this:

Filter: Sailing Launch

UserList:

John

Frank

You can click on the filter or on the user. To get to this stage, we clicked “Sailing”, and then “Frank” (perhaps we see a beautiful photograph of Frank in the middle of the screen).

My Redux state built with help combineReducersis as follows:

{
  ui: { 
    filter: {enjoys: 'Sailing'},
    userList: {selected: 'John'}
  }
  data: [user array]
}

I have two actions: SELECT_USERand SELECT_FILTER.

(SELECT_FILTER fires), , ui.userList.selected , , ui.userList.selected - null, .

, "Eating", Bob Frank , Frank . Running, , .

Redux. userList SELECT_FILTER, data, , .

?

function filter(state = {enjoys: null}, action) {
  switch (action.type) {
    case SELECT_FILTER:
      return {
        ...state,
        enjoys: action.enjoys
      }
    default:
      return state
  }
}

function userList(state = {selected: null}, action) {
  switch (action.type) {
    case SELECT_USER:
      return {
        ...state,
        selected: action.name
      }
    default:
      return state
  }
}

const ui = combineReducers({
  filter,
  userList
})

let initialUsers = [
  {
    name: 'John',
    enjoys: ['Sailing', 'Running']
  },
  {
    name: 'Bob',
    enjoys: ['Running', 'Eating']
  },
  {
    name: 'Frank',
    enjoys: ['Sailing', 'Eating']
  }
]

const rootReducer = combineReducers({
  ui,
  data: (state=initialUsers) => state // in reality, loaded from server
})

export default rootReducer
+4
3

.

. redux-thunk .

function selectFilter(enjoys) {
  return (dispatch, getState) => {
    dispatch({type: SELECT_FILTER, enjoys});
    // if getState().ui.userList.selected exists in getState().data
    dispatch({type: SELECT_USER, name: null});
  }
};
+2

.

, (componentWillUpdate componentWillReceiveProps), , . , .

, , FETCH_USERS_SUCCESS, .

+1

It must be machined with a filter gear. You need to send user data as part of the payload. Therefore, the reducer can calculate the selected user logic. You should consider adding a new action, as @cuttals suggested.

0
source

Source: https://habr.com/ru/post/1623389/


All Articles