我遇到的问题是ConnectedRouter没有更新路由更改的历史记录。 在路由更改存储获取更新的历史记录和路由器(ConnectedRouter的子)获取更新的历史记录,但ConnectedRouter的历史保持相同。该应用不会渲染新组件,但浏览器的网址会发生变化。
索引
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'react-router-redux'
import AppContainer from './containers/app'
import { history, store } from './store'
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<AppContainer />
</ConnectedRouter>
</Provider>,
document.getElementById('root')
)
存储
import createHistory from 'history/createBrowserHistory'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import { rootReducer } from './reducers/root'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
export const history = createHistory()
const middleware = routerMiddleware(history)
export const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(middleware))
)
rootReducer
import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
export const rootReducer = combineReducers({
router: routerReducer,
})
HeaderContainer
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { push } from "react-router-redux"
import { HeaderTemplate } from '../components/templates/header'
const mapStateToProps = state => ({})
const mapDispatchToProps = dispatch =>
bindActionCreators({
pushRoute: location => dispatch(push(location)),
}, dispatch)
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(HeaderTemplate)
)
HeaderTemplate中
import React from 'react'
export const HeaderTemplate = props => (
<div className="content">
<nav>
<ul>
<SomeLink onClick={() => props.pushRoute('/')}>Link1</SomeLink>
<SomeLink onClick={() => props.pushRoute('/test')}>Link2</SomeLink>
</ul>
</nav>
</div>
)
答案 0 :(得分:4)
看起来你正在做的是将 HeaderContainer 包裹在withRouter
中,但实际上应该用 AppContainer 包装,假设 AppContainer 在其中包含实际的<Route />
。
除此之外我唯一要说的就是确保你跑了:
npm install --save react-router-redux@next
答案 1 :(得分:0)
问题有点令人困惑,但我想我知道你的问题。我不相信路由器可以是ConnectedRouter的孩子,你需要用ConnectedRouter替换路由器,一切都会按预期工作。