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:
history.replace(this.state)
; then I move out of the page with history.push(newLocation)
componentWillMount
) I check for this.props.location.state !== undefined
and if so, I restore it with this.setState(this.props.location.state)
My question is: is the above pattern correct? suggested? Is there any better and widely adopted way?
after a while I found a reasonable workaround:
this.setState()
I keep state synchronized with history using window.history.replaceState({ key: history.location.key, state: this.state})
willMount
and willReceiveProps
) I check for state in props.params.location.state
: if there is one, I do restore it; if there is none I create a fresh new state.this.setState
and window.history.pushState
This solution seems to work nicely, the only minor cons are:
this.setState
is a pitfall because it's asynchronous, you cannot use this.state
after it, unless you do trickery. constructor()
of the Component
Overall I have written a PageComponent
that extends Component
that does all the init/restoration work; it also overrides this.setState
to make it syncs automatically with history and avoids the asynchronous annoyances.