简体   繁体   中英

Browser back button to reverse to previous redux state

I have an App from create-reat-app. Very simple app with nav menu element and content element. When i click on button in the nav menu dashboard element will load in the content element. Everything worked perfectly. Then i introduced react-router so all changes happened without refreshing the browser. All goo so far.

Then i started playing with redux. Navigation on the left is for certain branches of business (ie London, Birmingham). After clicking on one, its id will save into redux store under page.currentBranch. Then the dashboard element will render based on what is in redux. It work fine when clicking on each one, but when hitting back or forward button, the url will change but dashboard still shows the info from the last button clicked as the redux store is not changing on browser back or forward buttons.

I have tried connected router , redux first history and multiple articles about this as well as looked through stackoverflow but still cant make this work

I Have created my first ever sandbox for this so you can understand how its all set up. Iam sure iam doing fundemegntally something wrong but cant figure out what:-)

sandbox

Appreciate any help

Use the useLocation hook to listen to location changes.


const location = useLocation();

useEffect(() > {
  //...Update redux accordingly
}, [location]);

You could try using an useEffect hook and deleting/resetting the redux state to the wanted state:

useEffect(() => {
    return function cleanup() { restartReduxState() };  
}, []);

The cleanup function will run whenever the component unmounts, for instance, you click on a different page on your navigation bar.

If you arent using function components I think componentWillUnmount() function is the equivelent to that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM