11

安装 React Devtools 后,我可以通过以下方式获取存储:

$r.store.getState()

以及如何在没有 React Devtools 的情况下做到这一点?

4

4 回答 4

22

我处于无法为 window 分配任何东西的情况,也没有机会使用 react 或 redux 开发工具。

这显然是无证和脆弱的,但它似乎对我有用的几个不同的网站有 redux。在控制台中输出对状态的访问(经过细微调整的存储)。

假设您正在渲染对具有 id 的 dom 节点做出反应react-root

const appStates = []
const reactRoot = document.getElementById('react-root')
let base

try {
    base = reactRoot._reactRootContainer._internalRoot.current
} catch (e) {
    console.log('Could not get internal root information from reactRoot element')   
}

while (base) {
    try {
        state = base.pendingProps.store.getState()
        // This also sometimes works...
        // state = base.stateNode.store.getState()
        appStates.push(state)
    } catch (e) {
        // no state
    }
    base = base.child
}

console.log('Application States', appStates)
于 2019-09-12T14:50:46.880 回答
5

选项1

您可以在开发模式下附加商店window,然后您可以从控制台访问 if。

if(env === 'dev') { // only an example - you'll need to tailor this to your build system
    window.store = store;
}

现在您可以直接从控制台访问它:

store.getState()

选项 2(镀铬)

  1. 商店创建后console.log(store)
  2. 在控制台中,右键单击商店,然后选择Store as global variable.
  3. 您将获得一个新变量,名称为temp1(或 tempX,如果您创建了其他变量)。
  4. 现在您可以使用temp1.getState().

不要忘记清除控制台语句(通常作为构建的一部分完成)。

于 2018-03-28T18:02:02.000 回答
2

window我想最简单的方法是在您创建商店后立即将其分配给全局:

const myStore = createStore();

if(process.env.NODE_ENV !== 'production') {
  window.store = myStore;
}

稍后您可以在浏览器控制台中访问它,例如:

store.getState();
于 2018-03-28T18:02:48.550 回答
1

访问 store 的最简单方法可能是使用 react-redux 中的 Provider。当我们将 store 传递给这个组件时,它使元素树下的所有子节点都可以使用它。Store 是通过 React 的 context API 提供的。

因此,在 Provider 的子组件中,我们现在可以执行类似的操作

render() {
  const { store } = this.context;
  console.log(store)
  return(
  ...
  )
}

这与 react-redux 的 connect HOC 能够访问 store 的方式相同。

您还知道Redux有一个很棒的devtools chrome 扩展吗?这会保留我们的状态和操作的历史记录,以便您可以跟踪应用程序生命周期的变化。这可能是最好的解决方案!!

于 2018-03-28T18:18:14.867 回答