简体   繁体   中英

How to integrate Reselect in my React + Redux application?

I am implementing React + Redux application and finding difficulties to integrate Reselect into my application;

Below are my codes

store.js

  import "regenerator-runtime/runtime";
  import { createStore, applyMiddleware } from 'redux';
  import createSagaMiddleware  from 'redux-saga';
  import { createLogger } from 'redux-logger';
  import rootReducer from '../_reducers';
  import rootSaga from '../_sagas';

  const loggerMiddleware = createLogger();

  const sagaMiddleware = createSagaMiddleware()

  export const store = createStore(

      rootReducer,
      applyMiddleware(
          sagaMiddleware,
          loggerMiddleware
      )

  );

  sagaMiddleware.run(rootSaga)

action.js

  import { alertConstants } from '../_constants';

  export const alertActions = {
      successRequest,
      successResponse,
  };

  function successRequest() {
      return { type: alertConstants.SUCCESS_REQUEST };
  }

  function successResponse(message) {
      return { type: alertConstants.SUCCESS_RESPONSE, message };
  }

reducer.js

  import { alertConstants } from '../_constants';

  export function alert(state = {}, action){
    switch (action.type) {
     case alertConstants.SUCCESS_RESPONSE:
       return {
           message: action.message
       };
       default:
           return state 
    }
  }

this could be my selector.js , but it wont work!

  import { createSelector } from 'reselect';

  const alertMessage = state => state.alert

  export const makeGetAlertMessage = createSelector(
     alertMessage,
     message => state.alert.message
  )

Error: Uncaught ReferenceError: state is not defined

I should have a file named selector.js and create a selector for this reducer, Could anyone please help me write selectors for this particular method?

PS: I have referred the Reselect Documentation but I am not able to make it work.

From what I have read in the documentation, the createSelector will use the last argument of it's function to pass the previous arguments in the create selector.

So this would mean the argument you are getting here, would be the result of alertMessage

import { createSelector } from 'reselect';

const alertMessage = state => state.alert

export const makeGetAlertMessage = createSelector(
  alertMessage,
  alert => alert
)

If you just want to get the alert , you can just return that one. I think the sample you have pointed out in the documentation, concerning the tax, clearly shows what should be the expected input, and what you would receive as an input for your function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM