正在更新此问题以使用connected-react-router而不是react-router-redux,因为它与react-router v4不兼容。
当调度一个动作时,我似乎不能让我的路由工作。我怀疑这是因为我使用的sagas没有正确配置。
我有一个传奇故事:
import { call } from 'redux-saga/effects'
import { push } from 'connected-react-router'
//...
yield call(push, '/dashboard')推送功能不会将浏览器重定向到指定的路径,尽管webdev工具中的redux日志显示操作已成功调度。
顶级index.js文件如下所示:
import createSagaMiddleware from 'redux-saga'
import rootSaga from './redux/sagas'
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import logger from 'redux-logger'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import rootReducer from './redux/modules'
import { applyMiddleware, compose, createStore } from 'redux'
import { createBrowserHistory } from 'history'
import { routerMiddleware, connectRouter } from 'connected-react-router'
const history = createBrowserHistory()
const sagaMiddleware = createSagaMiddleware()
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore(
connectRouter(history)(rootReducer),
composeEnhancer(
applyMiddleware(
sagaMiddleware,
routerMiddleware(history),
logger
)
)
)
sagaMiddleware.run(rootSaga)
const render = () => {
ReactDOM.render(
<Provider store={store}>
<App history={history} />
</Provider>,
document.getElementById('root')
)
}
render()
registerServiceWorker()包含根组件的App.js文件具有:
import { ConnectedRouter } from 'connected-react-router'
import { Route, Switch, Redirect } from 'react-router-dom'
const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Switch>
{ routes }
</Switch>
</ConnectedRouter>
)
}
export default App此设置中缺少什么使其正常工作?
依赖项版本:
"react-redux": "^5.0.7",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"connected-react-router": "^4.3.0"发布于 2018-06-15 02:16:18
与history的push方法(这是一个不纯的函数)不同,connected-react-router的push是一个操作创建器,它的结果(操作)必须被分派以触发导航。
要在redux-saga中这样做,您必须使用put,而不是call。
call创建了一个调用效果。
当被生成时,它只是使用给定的参数执行给定的函数并返回一个结果。通过将我们从函数的直接执行中分离出来,它非常适合(但不限于)不纯函数调用(例如,网络请求)。
put创建调度效果。
当产生时,它调度传入的action对象。因此,只将你的代码从dispatch的直接调用中解耦,而不是动作创建者(这在设计上应该是纯粹的)。
因此,在您的情况下,解决方案将如下所示:
yield put(push('/dashboard'))附言:react-router-redux__的push也是如此
发布于 2018-06-10 17:27:34
您需要连接router's middleware,例如:
import { browserHistory } from 'react-router'
import { routerMiddleware } from 'react-router-redux'
const sagaMw = createSagaMiddleware()
const routerMw = routerMiddleware(browserHistory)
const middleware = applyMiddleware(sagaMw, routerMw, logger)发布于 2018-06-17 01:17:52
redux saga是作为生成器函数实现的,它为
-saga中间件生成对象
所以你的Saga应该导出一个Generator函数:
import { call } from 'redux-saga/effects'
import { push } from 'connected-react-router'
//...
export function* rootSaga() {
return yield call(push, '/dashboard')
}并且应该在sagaMiddleware中注册rootSaga
import { rootSaga } from './redux/sagas';
...
sagaMiddleware.run(rootSaga)
...参考:https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html
https://stackoverflow.com/questions/50755381
复制相似问题