从 `redux-thunk` 导入 thunk 在 stackblitz 中不起作用

问题描述 投票:0回答:1

现在我正在 Stackblitz 平台中尝试基本的 redux 逻辑。

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';

import taskReducer from './reducers/taskReducer';

const store = createStore(
  taskReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;

但是当我将此代码添加到 src/store.js 中时,预览面板只显示空白页面。 当更改此文件不使用 createStore 或 thunk 时,效果很好。 我基本上确定这段代码是正确的,并且我认为这只是 stackblitz 问题。

所以我想知道为什么会发生这种情况

感谢社区的帮助..

我现在正在尝试,希望 stackblitz 能正常工作。

reactjs redux redux-thunk stackblitz
1个回答
0
投票

readux-thunk@3
中不再有任何
default
导出,因此
require("redux-thunk").default
未定义。

比较 v2

...

const thunk = createThunkMiddleware() as ThunkMiddleware & {
  withExtraArgument<
    ExtraThunkArg,
    State = any,
    BasicAction extends Action = AnyAction
  >(
    extraArgument: ExtraThunkArg
  ): ThunkMiddleware<State, BasicAction, ExtraThunkArg>
}

// Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
thunk.withExtraArgument = createThunkMiddleware

export default thunk

v3

...

function createThunkMiddleware<
  State = any,
  BasicAction extends Action = AnyAction,
  ExtraThunkArg = undefined
>(extraArgument?: ExtraThunkArg) {
  // Standard Redux middleware definition pattern:
  // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
  const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
    ({ dispatch, getState }) =>
    next =>
    action => {
      // The thunk middleware looks for any functions that were passed to `store.dispatch`.
      // If this "action" is really a function, call it and return the result.
      if (typeof action === 'function') {
        // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
        return action(dispatch, getState, extraArgument)
      }

      // Otherwise, pass the action down the middleware chain as usual
      return next(action)
    }
  return middleware
}

export const thunk = createThunkMiddleware()

...

更新您的代码以导入 named

thunk
导出。

import { createStore, applyMiddleware } from 'redux';
import { thunk } from 'redux-thunk'; // <-- import named export
import { composeWithDevTools } from 'redux-devtools-extension';

import taskReducer from './reducers/taskReducer';

const store = createStore(
  taskReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;
© www.soinside.com 2019 - 2024. All rights reserved.