【问题标题】:Redux transition to after action executionRedux 过渡到操作执行后
【发布时间】:2016-01-28 09:23:07
【问题描述】:

我有一个动作像

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

  };
}

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

我在这里收到router is not defined

【问题讨论】:

  • router 应该在 this.props 上传递。
  • 它在我的行动中..我怎样才能在 this.props 中传递它..
  • 啊,看的不够仔细。你在用redux-router吗?
  • 是的,我正在使用它.. 我想重定向它.. 我看到它是正确的方式,但我的路由器没有定义
  • 如果你使用redux-router,那么导入pushState并调度。

标签: javascript react-router redux


【解决方案1】:

您必须将路由器传递给您的 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));

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

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

还有一件事。新的 react-router api 在路由器中没有 transitionTo 方法!不知道你用的是新的还是旧的api。但是如果你得到如下错误:

调用 transitionTo 失败:'location.search.substring 不是函数'

然后也改变:

router.transitionTo("/profile")

到:

router.push("/profile")

【讨论】:

  • 问题是我从我的组件中调用了这个动作,但我没有得到this 对象是动作..你能帮忙......
  • 是的,在你的问题中写下你的组件内容(如果可能的话,删除所有过时的代码)。
  • 但如果我不得不猜测更多。然后,您尝试在作为回调调用的方法中调用您的操作。您可以尝试在构造函数中添加:this.yourMethodWhichInvokeAction = this.yourMethodWhichInvokeAction.bind(this)
【解决方案2】:

外部组件可以使用history提供当前路由

import { browserHistory } from 'react-router'

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

【讨论】:

  • 它给出了与浏览器历史一致的结果..我不想要这个......如果你能解释一下我怎么能像 router.transitionTo("/profile ")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
相关资源
最近更新 更多