最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - componentWillMount executing twice - Stack Overflow

programmeradmin3浏览0评论

I am calling an API before mounting a ponent but my code calling an API twice. My requirement is to display year data after getting Successful API call(it will return year data). If I use setState function inside ponentWillMount then it should not call render method, but in my case render function is also called several times.

  ponentWillMount(){
        // Year api call
          var oauth=GetAuthToken()
        if(this.props.options.apiName === 'year__c' ){
          var access_token=oauth.then((data) => {
            var temp
            temp=GetYear(data.access_token)
            temp.then((obj) => {
              this.setState({
                year:obj
              })
            })
          })       
        }
    }

I am calling an API before mounting a ponent but my code calling an API twice. My requirement is to display year data after getting Successful API call(it will return year data). If I use setState function inside ponentWillMount then it should not call render method, but in my case render function is also called several times.

  ponentWillMount(){
        // Year api call
          var oauth=GetAuthToken()
        if(this.props.options.apiName === 'year__c' ){
          var access_token=oauth.then((data) => {
            var temp
            temp=GetYear(data.access_token)
            temp.then((obj) => {
              this.setState({
                year:obj
              })
            })
          })       
        }
    }
Share asked Dec 12, 2016 at 21:42 kunal krishnakunal krishna 951 silver badge8 bronze badges 1
  • 1 Just as a side ment, I tend to avoid setting the state in the ponentWillMount function since it will NOT trigger a re-render. Instead I use the ponentDidMount function for this. – Fizz Commented Dec 12, 2016 at 21:46
Add a ment  | 

1 Answer 1

Reset to default 8

The problem you are running into is that your setting state based off a promise being resolved. In a normal ponentWillMount you setState, it updates the state, and then render() is called for the first time. When you introduce asynchronous api calls into the picture, then what happens is:

ponentWillMount is executed, an API call is made and a Promise is created, while the Promise waits to be resolved code continues executing, React executes the Render() method on the ponent. At some point after rendering the Promise is resolved, setState is then called and since the Component has already been rendered then it will have to rerender due to a change in state.

The primary difference between the two being: If you just setState in the ponentWillMount then it will happen before render occurs. If you have setState as part of a Promise being resolved, it will happen after the ponent has rendered thus causing multiple renders.

发布评论

评论列表(0)

  1. 暂无评论