Redux 转换到操作执行后

Redux transition to after action execution

本文关键字:执行 操作 转换 Redux      更新时间:2023-09-26

我有一个这样的动作

export function loginSuccess(response){
    return (dispatch, getState) => {
    dispatch({ response, type: types.LOGIN });
    router.transitionTo("/profile")
  };
}
在这里,在

成功执行我的操作后,我想将其重定向到/profile

在这里我得到了router is not defined.

你必须将路由器传递给你的 redux thunk 动作创建者(你的代码不是一个动作,但正如我写的动作创建者)。例如,它可能看起来像:

export function loginSuccess(router, response){
  return (dispatch, getState) => {
    dispatch({ response, type: types.LOGIN });
    router.transitionTo("/profile")
  };
}

您是否有权访问调用此操作创建器的位置的路由器? 那里有吗? 如果是,那么你有这样的东西(我不知道response是什么):

this.props.dispatch(loginSuccess(response));

您必须将其更改为:

this.props.dispatch(loginSuccess(this.context.router, response));

我假设您可以通过上下文访问路由器。

因为你没有展示你如何调用这个动作,我只是猜测。我希望我的指示能帮助你。

还有一件事。新的反应路由器 API 在路由器中没有 transitionTo 方法!我不知道你使用的是新的还是旧的 api。但是,如果您收到以下错误:

调用transitionTo失败,并显示:"location.search.substring 不是函数"

然后也改变:

router.transitionTo("/profile")

自:

router.push("/profile")

外部组件 您可以使用历史记录来提供当前路由

import { browserHistory } from 'react-router'
export function loginSuccess(response){
    return (dispatch, getState) => {
    dispatch({ response, type: types.LOGIN });
    browserHistory.push("/profile")
  };
}