【发布时间】:2018-08-07 05:03:33
【问题描述】:
我目前正在开发一个 react redux 应用程序。当我在浏览器中使用上一个和下一个按钮导航时,url 正在更改并且路线得到正确呈现。但是,redux 存储保持最新状态并且不会跨导航进行时间旅行,唯一改变的状态是路由器位置状态。
这是我的 redux 商店:
import {applyMiddleware, combineReducers, createStore} from "redux";
import reducers from "../reducers";
import history from '../history'
import {routerMiddleware, routerReducer} from "react-router-redux";
const middleware = routerMiddleware(history)
const store = createStore(
combineReducers({
...reducers,
router: routerReducer
}),
applyMiddleware(middleware)
)
export default store
应用程序的索引文件是:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'semantic-ui-css/semantic.min.css';
import {registerObserver} from "react-perf-devtool";
import {Provider} from "react-redux";
import store from "./store";
import {ConnectedRouter} from "react-router-redux";
import history from './history'
if (module.hot) {
module.hot.accept()
}
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
registerObserver();
registerServiceWorker()
历史如下:
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
export default history
最后,这里是减速器:
import {SET_USER_LOCATION, SET_NEARBY_SHOPS} from "../constants/action-types";
const initialState = {
userLocation: {
latitude: 0.,
longitude: 0.
},
nearbyShops: {
shops: [],
radiusOfSearch: 0.
}
}
const userLocation = (state = initialState.userLocation, action) => {
switch (action.type) {
case SET_USER_LOCATION:
return { latitude: action.payload.latitude, longitude: action.payload.longitude }
default:
return state
}
}
const nearbyShops = (state = initialState.nearbyShops, action) => {
switch (action.type) {
case SET_NEARBY_SHOPS:
return { shops: [...action.payload.shops], radiusOfSearch: action.payload.radiusOfSearch }
default:
return state
}
}
const reducers = { userLocation, nearbyShops }
export default reducers
我使用推送导航到另一条路线:
const mapDispatchToProps = dispatch => bindActionCreators({
setNearbyShops: nearbyShops => setNearbyShops(nearbyShops),
goToNearbyShops: (latitude, longitude, radius) => push(`/nearby/@${latitude},${longitude},${radius}`)
}, dispatch)
我想要的是,当我在历史记录中来回导航时,userLocation 和 nearShops 状态会同步,因此组件会以正确的状态而不是最新状态呈现。
这是一个 gif,用于进一步解释我正在尝试解决的问题:
【问题讨论】:
-
嘿,我也有同样的问题,发在这里github.com/ReactTraining/react-router/issues/5974如果你解决了,请评论,这不是包问题
-
我一定会的!
-
嘿,所以我想我有一个最终答案给你,这个功能不是 react-router-redux 的一部分。您/我们正在寻找类似 @987654323@ 的东西,或者只是编写我们自己的中间件来通过会话存储处理浏览器 url 与数据状态的同步
-
或者一种方法是拦截浏览器的后退和下一步按钮,并以某种方式使其与 redux-undo 一起工作
标签: reactjs redux react-redux react-router-redux react-router-dom