Home>Q&A>body text

javascript - react uses fetch to accept data.

Using the react framework to make the front-end interface, now we need to determine the user type based on the data sent from the background to display different interfaces. However, a problem was discovered during actual operation, that is, the data requested by fetch is asynchronous. In practice, the interface has been rendered before the requested data is judged. I tried to judge in .then() in fetch, but the result is still the same. Is there any solution? Or my approach is wrong.


Originally I wanted to change the value of userType based on the incoming data, and then pass it into the component to change the display form of the component. Now userType does not change at all.
There is another problem. I tried doing .then() twice and printed the same content, but the second print was undefined.

某草草某草草 2678 days ago 893

reply all(2)I'll reply

  • 習慣沉默

    習慣沉默2017-05-19 10:14:19

    Put userType in state. After returning asynchronously, call setState to trigger the render of the component.

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:14:19

    There should be something wrong with your approach,

    你上面 有个this.setState(data:data);你这样 界面就渲染了;我不知道 你这个this.setState(data:data)作用是什么,但是setState()就会渲染页面, 看不到你其他的代码, 你把this.setState(data:data)放到userType判断的后面去 看看! 你传到组件的userType方式是 this.state.userType的话,this.setState(userType:userType),也是放到userType判断的后面,你可以把代码贴全点!

    reply
    0
  • Cancelreply