无法读取未定义的 属性 'type' (react-router-redux)

Cannot read property 'type' of undefined (react-router-redux)

我正在尝试在退出后重定向到该页面。但是,每次我注销时,它都会成功引导页面。但是,我仍然得到错误

Cannot read property 'type' of undefined

"Pause on Caught Exceptions"进一步研究,与react-router-redux有关。

所以下面代码中的 store.dispatch(push('/signin')) 行导致了这个问题。如果我改成.map(() => ({ type: 'NOT_EXIST' }));,就没有问题了。

这可能是什么原因造成的?谢谢

actions/auth.action.js

export const signOutSucceedEpic = (action$, store) =>
  action$
    .ofType(SIGN_OUT_SUCCEED)
    .map(() => store.dispatch(push('/signin')));  // <- this line causes the issue

actions/index.js

import { combineEpics } from 'redux-observable';

export default combineEpics(
  // ...
  signOutSucceedEpic
);

index.js

import { Provider } from 'react-redux';
import { Route } from 'react-router-dom';
import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import rootEpic from './actions/index';

const history = createHistory();
const routeMiddleware = routerMiddleware(history);
const epicMiddleware = createEpicMiddleware(rootEpic);

export const store = createStore(
  rootReducer,
  persistedState,
  composeWithDevTools(
    applyMiddleware(
      epicMiddleware,
      routeMiddleware
    )
  )
);

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <div>
        <Route path="/signin" component={SignIn} />
        <Route exact path="/" component={Home} />
      </div>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

问题是您在 map 运算符内调用 store.dispatch,映射到 store.dispatch() 的 return 值,但它没有 return 任何东西,因此值 undefined 由您的史诗发出,然后由 redux-observable 代表您发送。然后 react-router-redux 接收到 undefined 值,但它假设只有带有 type 属性 的动作才会被调度,所以它会导致有问题的错误。

我推荐 re-examining redux-observable 文档,因为直接在 epics 中调用 store.dispatch 是一个 anti-pattern,没有必要。您的史诗应该发出一系列操作,这些操作将由 redux-observable 为您分派,因此在这种情况下,您可以只删除 store.dispatch 并映射到 push() 操作的结果:

export const signOutSucceedEpic = (action$, store) =>
  action$
    .ofType(SIGN_OUT_SUCCEED)
    .map(() => push('/signin'));