【问题标题】:Cannot read property 'type' of undefined (react-router-redux)无法读取未定义的属性“类型”(react-router-redux)
【发布时间】:2018-01-05 20:55:57
【问题描述】:

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

无法读取未定义的属性“类型”

“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')
);

【问题讨论】:

  • 我想你忘了指定类型,这样写:store.dispatch({type: 'abc', data: push('/signin')}); 检查DOC 示例。

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


【解决方案1】:

问题是您在 map 运算符中调用 store.dispatch,映射到该 store.dispatch() 的返回值,但它不返回任何内容,因此值 undefined 正在由您的史诗发出然后由 redux-observable 代表您发送。然后 react-router-redux 接收到 undefined 值,但它假定只有具有 type 属性的操作将被调度,因此会导致相关错误。

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

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

【讨论】:

  • 非常感谢!!只需在此处输入正确的代码.map(() =&gt; push('/signin'));
  • 你在写一些废话。 push('/signin') 确实返回 undefined。看这里engineering.blogfoster.com/… 并用你的理论解释为什么dispatch(push('/signin')); 在该示例中工作正常并引发OP 的问题。
  • @Green 这个答案解决了他的特定问题。从react-router-redux 调用push 不会返回undefined,它会返回您调度的操作。直接用它调用 dispatch 确实会导致转换,但是如果你在 map 内执行它,你会收到与 OP 相同的错误,因为你的史诗应该总是发出动作,而不是 undefined。在史诗中直接使用store.dispatch 是一种反模式,将在redux-observable v1.0.0 中删除以防止混淆。相反,史诗应该发出中间件将为您调度的操作。
  • 我遇到了类似的问题。原来我正在调用一个连接到没有返回动作的调度程序的方法(它正在调度其他动作,但本身没有)。取消连接该方法解决了我的问题。
猜你喜欢
  • 2018-02-02
  • 1970-01-01
  • 2019-03-10
  • 2019-06-03
  • 2020-10-10
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
相关资源
最近更新 更多