使用 next-redux-wrapper 时访问 React 外部的 Redux 存储 [英] Access Redux store outside React when using next-redux-wrapper
问题描述
我有一个 NextJS React 应用程序,它在 _app.tsx
上使用 next-react-wrapper(基本上是一个 HOC),如下所示:
I have a NextJS React app that uses the next-react-wrapper (basically a HOC) on _app.tsx
like so:
_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 所需的(包括初始状态).
I'm struggling to work out how to access the store outside of React such as in a simple helper function. My store.ts
file exports a makeStore
function which is needed (including the initial state) for the next-redux-wrapper HOC.
我可以在 React 组件中访问存储,每次都将它作为参数传递给我的辅助函数,但这看起来很混乱.
I could access the store in a React component and pass it to my helper functions as an argument each time but that seems messy.
有没有办法直接从非 React 辅助功能模块访问 store?
Is there a way to access the store direct from non React helper function modules?
推荐答案
可能不太好,但是可以使用 storeKey
从窗口访问 store.默认键是 __NEXT_REDUX_STORE__
并且使用它看起来像这样:
It may not be preferable, but the store can be accessed from the window using a storeKey
. The default key is __NEXT_REDUX_STORE__
and using it look like this:
window.__NEXT_REDUX_STORE__.getState()
可以在传递给 withRedux 函数参数的第二个选项参数中更改密钥 (storeKey
).对于您的实现,它看起来像这样:
The key (storeKey
) can be changed in the second options parameter passed to the withRedux function parameter. For your implementation it looks like this:
export default (
initialState: any = undefined,
{ storeKey: 'whateveryouwant' } // the name on the exposed store variable
) => createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware()),
);
这篇关于使用 next-redux-wrapper 时访问 React 外部的 Redux 存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!