I have the following components:
App
: the root component, which contains the routes to other components using React Router DOM.
MovieScreen
, shown when visiting movies/:id
.
LoginScreen
, shown when the user needs to login before performing an action.
Consider this scenario:
The user visits /movies/awesome-movie
. MovieScreen
component is rendered and based on the ID, the movie data is fetched and displayed. Loading happens in useEffect()
.
The user tries to do an action that requires authentication, like marking the movie as watched. To authenticate, I show a link to the LoginScreen
, like this:
<Link to="/login">
<Button>Login</Button>
</Link>
The user presses the button and goes to LoginScreen
.
- In
LoginScreen
, the user presses the Back button and navigates back to MovieScreen
.
What happens now is that the movie data is re-loaded, losing any UI state. I'd like to avoid this situation.
As I understand, the React way to solve this is to "push state up".
An idea I have is to load the movie data in the App
component and only when it's loaded show MovieScreen
.
Is my idea a good solution? Are there other, better solutions?
question from:
https://stackoverflow.com/questions/65600847/prevent-api-call-in-component-when-navigating-back-to-it 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…