While debugging, can I have access to the Redux store from the browser console?

前端 未结 9 1194
难免孤独
难免孤独 2020-12-12 14:01

I have unit tests for my reducers. However, when I\'m debugging in the browser, I want to check if my actions have been called correctly and whether the state h

相关标签:
9条回答
  • 2020-12-12 14:54

    You can use a logging middleware as described in the Redux Book:

    /**
     * Logs all actions and states after they are dispatched.
     */
    const logger = store => next => action => {
      console.group(action.type)
      console.info('dispatching', action)
      let result = next(action)
      console.log('next state', store.getState())
      console.groupEnd(action.type)
      return result
    }
    
    let createStoreWithMiddleware = applyMiddleware(logger)(createStore)
    
    let yourApp = combineReducers(reducers)
    let store = createStoreWithMiddleware(yourApp)
    

    Alternatively, you could change the logging to just append to a global array (your window._redux) and you could look in the array when you needed information on a particular state.

    0 讨论(0)
  • 2020-12-12 14:58

    Another answer suggests adding the store to the window, but if you just want access to the store as an object, you can define a getter on the window.

    This code needs to be added where you've configured your store - in my app, this is the same file as where <Provider store={store} /> is called.

    Now you can type reduxStore in the console to get an object - and copy(reduxStore) to copy it to the clipboard.

      Object.defineProperty(window, 'reduxStore', {
        get() {
          return store.getState();
        },
      });
    

    You can wrap this in an if (process.env.NODE_ENV === 'development') to disable it in production.

    0 讨论(0)
  • 2020-12-12 15:01

    With react developer tools:

    const store = [...__REACT_DEVTOOLS_GLOBAL_HOOK__.reactDevtoolsAgent.internalInstancesById.values()].find(e=>e.elementType.name==="Provider").pendingProps.store
    
    0 讨论(0)
提交回复
热议问题