Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - Prevent API call in component when navigating back to it

I have the following components:

  1. App: the root component, which contains the routes to other components using React Router DOM.
  2. MovieScreen, shown when visiting movies/:id.
  3. LoginScreen, shown when the user needs to login before performing an action.

Consider this scenario:

  1. 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().

  2. 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.

  1. 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?


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

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...