When I used fetch to improve the interface data of the react project today, I encountered a difficult problem.
The business logic is: first determine the user's identity, and then display the corresponding interface for him.
But fetch obtains data asynchronously, and the result appears. The page is first rendered, and then the data is requested back (the data request is slower than the page rendering), and then the display status of the page is changed through state.
This is how it appears. The page first displays an interface, and then after 1 to 2 seconds, the status changes and the interface changes again. The user experience is very poor. Is there any solution?
It is best to accept the data first, then complete the judgment, and then render the interface.
This is actually very simple. You do a ternary operator in the return of render. Determine whether the data has been obtained.
Another idea is to write fetch in render and put the return template in fetch's then callback, so that you can obtain the data and then render it. I haven't tested it yet, but it should be possible.
If you think my answer has solved your problem, please click
采纳答案
If you have any questions, please ask in the comment area.
Get a loading prompt box,
Wait until the data request is completed before rendering the page
Save the user’s identity status in localStorage first, and fetch it from localStorage for the first time