You need to think about what your "single source of truth" is here.
One approach is to keep the toggle switch state in the URL only and out of redux. When flipping the switch, you would update the URL by using history.push
. The history
would contain all of the previous states and slugs.
Storing it in both places is actually more complicated. You would need to use useEffect
hooks at the highest level of your app to trigger changes in the URL and the store to make sure that they stay in sync with each other. You would have a useSelector
which gets the current redux switch state, and that value would be one of the dependencies of a useEffect
. When the redux state changes, see if it matches the URL. If not, use history.push
to update the URL so that they match. A second useEffect
hook would be triggered by changes in the URL and would dispatch a change to the redux store if they are out of sync. Be careful as it's easy to create an infinite loop with this setup if you aren't making your changes conditionally (only when there is a mismatch) or if your changes don't create a match.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…