I have a project that redux working on. But when I click on a <Link>
component or click on to the “previous page” button on chrome, redux keeps the states I changed before. I tried the LOCATION_CHANGE
action from connected-react-router
and use it in reducer but it does not seem to work.
reducer:
JavaScript
x
11
11
1
import {LOCATION_CHANGE} from "connected-react-router"
2
function reducer(state=defaultState,action) {
3
switch (action.type) {
4
case LOCATION_CHANGE:
5
console.log("changed")
6
return defaultState
7
default:
8
return state
9
}
10
}
11
Advertisement
Answer
You can try something like this :
JavaScript
1
15
15
1
class ScrollToTop extends Component {
2
componentDidUpdate(prevProps) {
3
if (this.props.location !== prevProps.location) {
4
window.scrollTo(0, 0);
5
dispatch({ type: LOCATION_CHANGE });
6
}
7
}
8
9
render() {
10
return this.props.children
11
}
12
}
13
14
export default withRouter(ScrollToTop)
15
JavaScript
1
8
1
const App = () => (
2
<Router>
3
<ScrollToTop>
4
<App/>
5
</ScrollToTop>
6
</Router>
7
)
8