我有一个 NextJS React 应用程序,它在 _app.tsx
上使用 next-react-wrapper(基本上是一个 HOC),如下所示:
_app.tsx
...
import withRedux from 'next-redux-wrapper';
class Page extends App<Props> {
...
}
export default withRedux(reduxStore)(Page);
store.ts
import { applyMiddleware, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import rootReducer from './reducer';
export default (
initialState: any = undefined,
) => createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware()),
);
我正在努力研究如何在 React 之外访问商店,例如在一个简单的辅助函数中。我的 store.ts
文件导出了一个 makeStore
函数,它是 next-redux-wrapper HOC 所需要的(包括初始状态)。
我可以在 React 组件中访问商店并将其作为参数每次传递给我的辅助函数,但这看起来很困惑。
有没有办法从非 React 辅助功能模块直接访问商店?
最佳答案
这可能不是首选,但可以使用 storeKey
从窗口访问商店。默认键是 __NEXT_REDUX_STORE__
并且使用它看起来像这样:
window.__NEXT_REDUX_STORE__.getState()
可以在传递给 withRedux 函数参数的第二个选项参数中更改 key (storeKey
)。对于您的实现,它看起来像这样:
export default (
initialState: any = undefined,
{ storeKey: 'whateveryouwant' } // the name on the exposed store variable
) => createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware()),
);
关于javascript - 使用 next-redux-wrapper 访问 React 外部的 Redux store,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56805679/