redux action如何做路由跳转?

如题。
项目中引入了react-router-redux,我去查了下api,官方的用法是这样的:

import { createStore, combineReducers, applyMiddleware } from 'redux';
import { routerMiddleware, push } from 'react-router-redux'

// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
  reducers,
  applyMiddleware(middleware)
)

// Dispatch from anywhere like normal.
store.dispatch(push('/foo'))

我的store只在我的入口文件里面创建了一次,所以我试着直接用

// action文件
import { push } from 'react-router-redux'

//...do something

dispatch(push('/home'))

触发这个action的时候却并没有跳转。我想请教下有没有用过的大神,教下应该怎么用。


有人问,那我就简单说下吧。

// index.js 入口文件
import {createStore, applyMiddleware} from 'redux'
import {syncHistoryWithStore, routerMiddleware } from 'react-router-redux'
import reducer from './Redux/Reducer'
import thunk from 'redux-thunk'

// 这里继续引入 `routerMiddleware` 通过 `history` 生成一个实例。
// 举个栗子
const middleware = routerMiddleware(browserHistory)

// 导入到 `store` 中
const store = createStore(
    reducer,
    applyMiddleware(middleware),
    applyMiddleware(thunk)
)

const history = syncHistoryWithStore(browserHistory, store)

// 后面的流程都一样了,再将 `history` 和 `store` 绑定到 `Route` 和 `Provider` 上就行了。
// 子模块
import { push } from 'react-router-redux'

// 事件函数中
let xxx = () => {
    // ...
    const { dispatch } = this.props
    dispatch(push('/路由'))
}

// 这样就能完成跳转了
阅读 14.3k
2 个回答

我补充一下,如果用redux-saga,想在saga中跳转路由可以这样做:

import createHistory from 'history/createHashHistory'
const history = createHistory()

//saga中使用:
history.replace(url)

上面的答案仅适用hashHistory模式,在browserHistory里好像history.replace或者history.push都是不会替换成功。
所以:
在browserHistory里,采用saga回调函数的方式去解决:

//action.js
//在action中
export const todo = (params, callback) => {
  return {
        type: TODO,
        params: params,
        onSuccess: callback || null
  }
}    
//saga.js
function* todo() {
  while(true) {
    try {
      // ...
      yield call(onSuccess)
    } catch(error) {
    //error
    }
  }
}
//组件内dispatch action
this.props.todo(params, () =>  this.context.router.history.push(url))

刚吃饭去了,忘了说了。问题已经解决了,解决的方法就是在createStore的时候传入一个routerMiddleware(history)创造出来的middleware就行了。然后在action中导入push,路由机会能跳转了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题