调试时,我可以从浏览器控制台访问 Redux 存储吗?

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

我有 reducers 的单元测试。但是,当我在浏览器中调试时,我想检查我的动作是否被正确调用,状态是否被相应地修改。

我正在寻找类似的东西:

window._redux.store

...在浏览器中,这样我就可以在控制台上输入它并检查进展情况。

我怎样才能做到这一点?

您可以使用日志记录中间件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)

或者,您可以将日志记录更改为仅附加到全局数组(您的 window._redux),当您需要有关特定状态的信息时,您可以查看该数组。

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

现在您可以在控制台中从 window.store 访问商店,如下所示:

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

如何在不更改代码的情况下在任何网站上查看 redux store

2019 年 11 月更新

自从我最初的回答以来,react devtools 已经改变了。 chrome 的 devtools 中的新 components 选项卡仍然有数据,但您可能需要多搜索一点。

  1. 打开 chrome 开发工具
  2. select 反应 devtool 的 Components 选项卡
  3. 单击最顶部的节点并在右侧列中查找要显示的 store
  4. 沿着树重复第 3 步,直到找到 store(对我来说是第 4 层)
  5. 现在您可以使用 $r.store.getState()
  6. 按照以下步骤操作

原答案

如果您有 React 开发者工具 运行,您可以使用 $r.store.getState();无需更改您的代码库

注意:你必须先在你的开发者工具window中打开react devtool才能使这个工作,否则你会得到一个$r is not defined错误

  1. 打开开发者工具
  2. 单击 React 选项卡
  3. 确保提供者节点(或最顶层节点)是 selected
  4. 然后在控制台中输入 $r.store.getState();$r.store.dispatch({type:"MY_ACTION"})

如果您想查看存储状态以进行调试,您可以这样做:

#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)

如果您使用的是 Next JS,您可以通过以下方式访问商店:window.__NEXT_REDUX_STORE__.getState()

您还可以调度操作,只需查看您选择的选项在 window.__NEXT_REDUX_STORE__

使用 React 开发者工具:

const store = [...__REACT_DEVTOOLS_GLOBAL_HOOK__.reactDevtoolsAgent.internalInstancesById.values()].find(e=>e.elementType.name==="Provider").pendingProps.store

首先,您需要在 window 对象中定义商店(您可以将其放在 configureStore 文件中):

window.store = store;

那么你只需要在控制台中写入以下内容:

window.store.getState();

希望这有帮助。

另一个答案建议将商店添加到 window,但如果您只想将商店作为对象访问,您可以在 window 上定义一个 getter。

此代码需要添加到您配置商店的位置 - 在我的应用程序中,此文件与调用 <Provider store={store} /> 的位置相同。

现在您可以在控制台中键入 reduxStore 来获取一个对象 - 然后 copy(reduxStore) 将其复制到剪贴板。

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

您可以将其包装在 if (process.env.NODE_ENV === 'development') 中以在生产中禁用它。

推荐的解决方案对我不起作用。

正确的命令是:

$r.props.store.getState()