【问题标题】:Redux save store as global variable on React appRedux 将 store 保存为 React 应用程序上的全局变量
【发布时间】:2017-09-30 16:41:49
【问题描述】:
import store from './store'

let reduxStore = ''
store.subscribe(() => {
  reduxStore = store.getState().username
  console.log(reduxStore) // I get USERNAME
})

console.log(reduxStore) // I get undefined

有没有办法将reduxStore 保存到全局变量中,以便我可以在store.subscribe 函数之外使用?

谢谢!

【问题讨论】:

  • 是什么阻止你使用let reduxStore = store.getState().username?
  • 它不会在订阅之外获得状态。我试过了,它给了我 undefined
  • 嗯,这很奇怪,它适用于我的示例:jsfiddle.net/ypnnkjk7/87。 (您需要向下滚动才能看到示例)
  • 顺便说一句....... reduxStore 它不是一个全局变量,它只作用于当前模块。
  • 知道如何设置reduxStore 以用于另一个函数吗?

标签: javascript reactjs redux store


【解决方案1】:

只需将您创建的商店分配给window:

const store = createStore(reducers, preloadedState);

// ...

window.reduxStore = store;

然后您可以从任何地方访问商店,例如: window.reduxStore.getState().username

但是,我想不出任何必要的正当理由。

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多