使用 next-redux-wrapper 时访问 React 外的 Redux 存储

Coo*_*oop 13 javascript reactjs redux next.js next-redux-wrapper

我有一个 NextJS React 应用程序,它使用 next-react-wrapper(基本上是一个 HOC),_app.tsx如下所示:

_app.tsx

...
import withRedux from 'next-redux-wrapper';

class Page extends App<Props> {
  ...
}

export default withRedux(reduxStore)(Page);
Run Code Online (Sandbox Code Playgroud)

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()),
);
Run Code Online (Sandbox Code Playgroud)

我正在努力研究如何在 React 之外访问商店,例如在一个简单的辅助函数中。我的store.ts文件导出了makeStorenext-redux-wrapper HOC 所需的函数(包括初始状态)。

我可以在 React 组件中访问 store 并将其作为参数每次传递给我的辅助函数,但这看起来很混乱。

有没有办法直接从非 React 辅助功能模块访问商店?

Fyo*_*dor -1

您可以创建高阶函数来用 store 包装任何其他函数。这是将 store 作为参数传递给任何其他函数的简单示例this

function withReduxFunction(store) {
    return function (connectedFunction) {
        return function (...args) {
            connectedFunction.call(store, ...args);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和用法。例如我们想为此函数提供存储

function doSomthingWothStore(arg1, arg2) {
    console.log(this);   // This will be store
    console.log("arg1: " + arg1 + " arg2 " + arg2);
}
Run Code Online (Sandbox Code Playgroud)

const funcWithStore = withReduxFunction(store)(doSomthingWothStore);
Run Code Online (Sandbox Code Playgroud)

现在你可以调用funcWithStore并且this将等于存储。

您可以使用高阶函数来使其适合您(即将 store 作为第一个参数传递,等等)。

您还可以查看react-reduxuseDispatch和hooks 。它们还应该与任何函数一起工作。useSelector