bind(this) not working on ajax success function

前端 未结 1 1646
清歌不尽
清歌不尽 2020-12-11 05:39

I use react and jQuery. here\'s a part of my code.

Before react component mounts, I perform ajax request to know if user is logged in.

It is supposed to set

相关标签:
1条回答
  • 2020-12-11 05:49

    I think you shouldn't use an Ajax call for setState in componentWillMount; do it in componentDidMount.

    If you don't want to do the first render before you're having data AND those data are just for initialization perform your call outside and on success render your view with the fetched data =====>

    <Myview data={initialDataFromTheCallSuccess} /> and then put it in getInitialState
    

    Read this if you choose this path (cause as stated in the doc this is not an anti-pattern on certain conditions): https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

    hope it helps

    Edit: There is two way to do it the first one you fetch outside your react class

      $.ajax({...}).success(function(res) {
          <MyView data={res} /> // render your function on success
      });
    

    and in MyView you getInitialState from props "data". Use this method only if you need to call your get once (read the anti-pattern stuff).

    Other method is doing what you are doing but in componentDidMount. https://facebook.github.io/react/tips/initial-ajax.html

    Hope it's clearer

    0 讨论(0)
提交回复
热议问题