更新此问题以使用 connected-react-router
而不是 react-router-redux
因为它与 react-router
不兼容v4.
我似乎无法在分派(dispatch) Action 时让我的路由正常工作。我怀疑这是因为我使用的 sagas 配置不正确。
我有一个传奇:
import { call } from 'redux-saga/effects'
import { push } from 'connected-react-router'
//...
yield call(push, '/dashboard')
尽管 webdev 工具中的 redux 日志显示操作已成功分派(dispatch),但推送功能不会将浏览器重定向到指定路径。
顶级 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"
最佳答案
不同于history
的push
方法(这是一个不纯的函数),connected-react-router
的push
是一个action creator,其结果(action)必须被分派(dispatch)以触发导航。< br/>
要在 redux-saga
中这样做,您必须使用 put
,而不是 call
。
call
创建一个call 效果。
当 yielded 时,它简单地执行带有给定参数的给定函数并返回结果。通过将我们与函数的直接执行解耦,它非常适合(但不限于)不纯函数调用(例如网络请求)。
put
创建一个调度效果。
产生时,它会分派(dispatch)传入的操作对象。因此,将您的代码仅与 dispatch
的直接调用分离,而不是 action creator(这应该是纯粹的设计)。
因此,在您的情况下,解决方案如下所示:
yield put(push('/dashboard'))
附言:react-router-redux
的 push
也是如此
关于reactjs - React redux 不会改变路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755381/