我目前正在开发一个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我使用push导航到另一条路径:
const mapDispatchToProps = dispatch => bindActionCreators({
setNearbyShops: nearbyShops => setNearbyShops(nearbyShops),
goToNearbyShops: (latitude, longitude, radius) => push(`/nearby/@${latitude},${longitude},${radius}`)
}, dispatch)我想要的是,当我在历史记录中来回导航时,userLocation和nearbyShops状态会同步,这样组件就会呈现正确的状态,而不是最新的状态。
下面是一个gif,用来进一步解释我正在尝试解决的问题:

发布于 2018-02-28 00:51:27
所以你想让你的UI直接依赖于历史状态。不幸的是,这对于react-router的现有redux包装器来说是相当麻烦的。
因此,当历史记录发生更改时,您的App组件将收到一个适当的更新。你必须以某种方式将这些新的道具转发给应该对它们做出反应的组件。例如,您可以在App组件的方法componentWillReceiveProps中将新信息分派到存储区。
或者,您可以通过多个组件层将道具转发到需要它们的地方,但我建议您不要这样做。
或者,尝试https://github.com/mksarge/redux-first-routing,这会使imho更有意义。它使路由独立于组件。另请参阅本文:https://medium.freecodecamp.org/an-introduction-to-the-redux-first-routing-model-98926ebf53cb
无论如何,userLocation和nearbyShops不应该是缩减,而应该是选择器,因为它们的信息可以而且应该从您历史上的地理位置派生出来。
https://stackoverflow.com/questions/49010550
复制相似问题