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

前端 未结 9 1193
难免孤独
难免孤独 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:38

    First of all, you need to define the store in the window object (You can place it in you configureStore file):

    window.store = store;
    

    Then you only need to write in the console the following:

    window.store.getState();
    

    Hop this helps.

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

    How to view redux store on any website, with no code changes

    Update Nov 2019

    The react devtools have changed since my original answer. The new components tab in chrome's devtools still has the data, but you may have to search a little bit more.

    1. open chrome devTools
    2. select react devtool's Components tab
    3. click on the top-most node and look in right-hand column for store to be shown
    4. repeat step 3 down the tree until you find the store (for me it was the 4th level)
    5. Now you can follow the steps below with $r.store.getState()

    Original Answer

    If you have react developer tools running you can use $r.store.getState(); with no changes to your codebase.

    Note: You have to open the react devtool in your developer tools window first to make this work, otherwise you will get a $r is not defined error

    1. open developer tools
    2. click the React tab
    3. ensure the provider node (or topmost node) is selected
    4. then type $r.store.getState(); or $r.store.dispatch({type:"MY_ACTION"}) into your console
    0 讨论(0)
  • 2020-12-12 14:42

    If you're using Next JS, you can access the store by: window.__NEXT_REDUX_STORE__.getState()

    You can also dispatch actions, just look at the options you have in window.__NEXT_REDUX_STORE__

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

    The recommended solution doesn't work for me.

    The correct command is:

    $r.props.store.getState()
    
    0 讨论(0)
  • 2020-12-12 14:47

    In case you would like to see store state for debugging you could do this:

    #import global from 'window-or-global'
    const store = createStore(reducer)
    const onStateChange = (function (global) {
      global._state = this.getState()
    }.bind(store, global))
    store.subscribe(onStateChange)
    onStateChange()
    console.info('Application state is available via global _state object.', '_state=', global._state)
    
    0 讨论(0)
  • 2020-12-12 14:48

    let store = createStore(yourApp); window.store = store;

    Now you can access the store from window.store in the console like this:

    window.store.dispatch({type:"MY_ACTION"})

    0 讨论(0)
提交回复
热议问题