I am building a small App to learn React with Meteor.
The user is asked to input a location, based on this location the user gets routed to a new page, where the location is displayed on the top of the page and some data from the database based on that location (not yet, this is my next step).
I store the location in state on the component. Now it would be nice if the user could change the location.
This is easy: just update state, e voilá. Or so I thought. The problem now is that the URL doesn't update, which looks dumb.
I then thought: "Okay, lets check on click if old location (in state) and new location (from input) are different, and if so set a redirect state"
In my render function if redirect is set I would just route the user to the same page again, but now the page won't reload. Any Ideas?
I know there are a thousand questions on react router v4 out there right now, because they just updated the version recently. I have been reading documentation for the last hours and just can't wrap my head around it.
Any explanation regarding the problem in basic language would also be extremely appreciated. I am just not there yet :(
Cheers and thx alot
解决方案
You can't expect to change the route just by changing the state. Even with the <Redirect> approach that you have used, it only make an infinite redirect loop by setting this.state.redirect true. Because Route use same LocationDisplay instance with each redirect and this.state.redirect will be always true. However, react-router automatically directs this redirect loop and renders a blank.
The correct way to change routes in react-router is use push method in history object. You can simply call push method with your new path name as follows.
Also, I don't understand why you keep locationId in your state. It's already in your props at this.props.match.params.locationId. So there is no point of keep same data in two places because having a single source of truth is ideal. Otherwise, you always have to write additional code lines to keep locationId in state and props sync. So I suggest you to, change your approach to something like this.
(This code is just to get an idea. I didn't test this code as I don't have other parts. If you can provide codepen or jsfiddle with your current implementation I can update it to work.)