安装了 React Devtools 后,我可以通过以下方式获取商店:
$r.store.getState()
如果没有 React Devtools 如何做到这一点?
我处于无法向窗口分配任何内容的情况,也没有机会使用 React 或 Redux 开发工具。
这显然是无证且脆弱的,但它似乎对我来说在几个具有 redux 的不同网站上都有效。输出对控制台内状态的访问(经过细微调整的存储)。
假设您正在对 id 为
react-root
的 dom 节点做出反应。
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)
选项1
当您处于开发模式时,您可以将商店附加到
window
,然后您可以从控制台访问。
if(env === 'dev') { // only an example - you'll need to tailor this to your build system
window.store = store;
}
现在您可以直接从控制台访问它:
store.getState()
选项 2(镀铬)
console.log(store)
。Store as global variable
。temp1
(如果您创建了其他变量,则为 tempX)。temp1.getState()
。不要忘记清除控制台语句(通常作为构建的一部分完成)。
我想最简单的方法是在创建商店后立即将其分配给全局
window
:
const myStore = createStore();
if(process.env.NODE_ENV !== 'production') {
window.store = myStore;
}
稍后您可以在浏览器控制台中访问它,例如:
store.getState();
访问存储的最简单方法可能是使用react-redux 中的Provider。当我们将存储传递给该组件时,元素树中的所有子组件都可以使用该存储。商店可通过 React 的上下文 API 访问。
因此,在 Provider 的子组件中,我们现在可以做类似的事情
render() {
const { store } = this.context;
console.log(store)
return(
...
)
}
这与 React-Redux 的 connect HOC 访问存储的方式相同。
您还知道 Redux 有一个很棒的 devtools chrome 扩展吗?这会保留我们的状态和操作的历史记录,以便您可以跟踪应用程序生命周期的变化。这可能是最好的解决方案!!
这是我的 Typescript 版本。我必须将 Redux 存储添加到窗口对象,但是是在带有 Typescript 的 SPFx(Sharepoint Online)解决方案中。我在 App.tsx 组件中的
return()
方法之前添加了此代码,我还导入了商店并将其插入到 :
import { Provider } from "react-redux";
import { store } from "../../../store/store";
export const App = (): ReactElement => {
(window as Window & typeof globalThis & { store: any }).store = store;
return (...)
}
然后您可以通过输入
window.store.getState()
在浏览器控制台中访问商店