Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

reactjs - Sync redux state with url paths

I have a toggle switch as one of my component and I want to sync it with my url. Lets consider I have 3 routes (/abc, /lmn, /xyz) when my toggle is OFF. When user switch ON the toggle I get routes like (/abc-t, /lmn-t, /xyz-t).

My toggle switch state is in redux.

Now suppose, when my switch is in OFF state and I'm on /abc route and I switch ON my toggle which fires an action in redux then I switch from /abc to /abc-t route and when I hit the back button I do navigate to /abc route but the switch remains in ON state.

Also if user enters a url I want to switch the toggle depending on the condition.

Is there a way to sync that switch/toggle state with url route? or any way to store all previous states?

question from:https://stackoverflow.com/questions/65835268/sync-redux-state-with-url-paths

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...