javascript - Questions about using fetch to request data in react
phpcn_u1582
phpcn_u1582 2017-05-18 11:00:17
0
3
533

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.

phpcn_u1582
phpcn_u1582

reply all(3)
洪涛

This is actually very simple. You do a ternary operator in the return of render. Determine whether the data has been obtained.

<p>
{this.state.data==null?<p></p>:<YourTemplate/>}
</p>

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template