I'm trying to figure out how to make my React SPA app maintain state when the user navigates with the back/forward browser buttons. E.g. the user is filling a form, then he moves back and forward and the form is automatically restored.
I reviewed many JavaScript routers around but none seem to address this issue properly... (or even at all).
Currently I'm using React Router 4 and this is the pattern I'm adopting:
- when programmatically leaving the page, I first save current page's state with
history.replace(this.state)
; then I move out of the page withhistory.push(newLocation)
- when a page component is created (
componentWillMount
) I check forthis.props.location.state !== undefined
and if so, I restore it withthis.setState(this.props.location.state)
My question is: is the above pattern correct? suggested? Is there any better and widely adopted way?
history.push
andhistory.replace
have the same function signature,(path, [state])
. Then why are you usinghistory.replace
with state as 2nd parameter ? I think you must use simplyhistory.push(newLocation, this.state)
instead of the 2 calls – Googlyhistory.push
to be meant as "the state of the current page that will get restored in case of back button" or is it "the state that the new page will take" ? This is very confusing. – Demantoidhistory.replaceState()
after everythis.setState()
to keep the current state updated (synchronized)? – Demantoid