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

标签 javascript reactjs react-redux react-router-redux redux-observable

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

Cannot read property 'type' of undefined

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

enter image description here

所以下面代码中的 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() 的返回值> 但它不返回任何内容,因此值 undefined 由您的史诗发出,然后由 redux-observable 代表您发送。然后 react-router-redux 接收到那个 undefined 值,但它假设只有具有 type 属性的 Action 才会被调度,所以它会导致有问题的错误。

我建议重新检查 redux-observable 文档,因为直接在你的史诗中调用 store.dispatch 是一种反模式,而且没有必要。你的史诗应该发出一系列 Action ,这些 Action 将由 redux-observable 为你分派(dispatch),所以在这种情况下你可以只删除 store.dispatch 并映射到 push 的结果() Action :

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

关于javascript - 无法读取未定义的属性 'type' (react-router-redux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45396343/

相关文章:

javascript - 下划线模板添加额外的 <h2> 标签

javascript - Post Ajax 函数返回 true 或 false

reactjs - React 中的容器应该可重用吗?

javascript - React.cloneElement 不附加 className

reactjs - axios post请求发送表单数据

javascript - 在页面加载时运行 TamperMonkey 脚本

javascript - 是否有一个好的框架或方法来重构 JavaScript 对象?

css - 不使用 Webpack 将 css 导入 jsx

reactjs - 如何使用 React 和 Redux 访问另一个组件的 ref?

reactjs - Redux 在 React 中添加了另一个数组中的对象数组