Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 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?

question from:https://stackoverflow.com/questions/65600847/prevent-api-call-in-component-when-navigating-back-to-it

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...