How to wait for AJAX response and only after that render the component?

后端 未结 4 1862
粉色の甜心
粉色の甜心 2020-12-04 12:27

I have a problem with one of my React components. I think AJAX doesn\'t load all the content from external server before React renders the ChildComp component.<

4条回答
  •  Happy的楠姐
    2020-12-04 13:04

    I threw it into a JSBin and I can't seem to reproduce your problem.

    http://jsbin.com/jefufe/edit?js,output

    Every time the button is clicked, it sends new props to , which then triggers its componentWillReceiveProps, sends the (fake) ajax request, receives the (fake) response, sets the response state to the (fake) response, and re-renders the component with the correct data shown.

    The only thing I added was a check for index.id == null before trying to access it, but I don't think that does anything to solve the issue you're having about being unable to access index.order.id.

    The only reason I can come up with as to why you can't access index.order.id is because perhaps you have some code that you aren't showing us that modifies the response at some point.

    Also, remember that React components will always re-render when its state or props have changed, unless you have defined behavior in shouldComponentUpdate that says otherwise. This means that when you receive the whole object from the server and set it to a state in your component, it will re-render and show you the updated state. There is no reason/way for React to "shallowly render" your response object like you were suggesting in your original post.

    I'm not sure if this answer helps, but hopefully you can look at the JSBin I provided and find something that you might have overlooked.

提交回复
热议问题