Home  >  Q&A  >  body text

javascript - Questions about using fetch to request data in react

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_u1582phpcn_u15822710 days ago487

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-05-18 11:02:17

    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.

    reply
    0
  • 高洛峰

    高洛峰2017-05-18 11:02:17

    Get a loading prompt box,
    Wait until the data request is completed before rendering the page

    reply
    0
  • 迷茫

    迷茫2017-05-18 11:02:17

    Save the user’s identity status in localStorage first, and fetch it from localStorage for the first time

    reply
    0
  • Cancelreply