如题。
项目中引入了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('/路由'))
}
// 这样就能完成跳转了
我补充一下,如果用redux-saga,想在saga中跳转路由可以这样做:
上面的答案仅适用hashHistory模式,在browserHistory里好像history.replace或者history.push都是不会替换成功。
所以:
在browserHistory里,采用saga回调函数的方式去解决: