简体   繁体   中英

re-render component without setting state react js

I am deleting a record from db, for this I am calling an API. When I received an API response of a successful deletion, I need to re-render all the component again like reload does. I tried it with this.forceUpdate and shouldComponentAgain but no luck.

I also tried with componentDidUpdate , it works but it is calling API infinite times. Below is my code how I used componentDidUpdate :

componentDidUpdate(){
  let newThis = this;
  getAccounts().then(function(response){
    if(response.status===200){
      newThis.setState({
        Accounts:response.data
      })
    }
  });
}

Please tell me the way to re-render like reload do, but without re-loading the whole page.

When using componentDidUpdate , you should always have a conditional setState which denotes that you need to perform something because the current state or current props is not equal to previous state or props.

componentDidUpdate always gets called whenever your component has updated. In your case what is happening is that you are calling setState without any condition which updates your component, and setState is called again causing an infinite loop in updating the component.

You should have something like this check here:

componentDidUpdate(prevProps, prevState){
  let newThis = this;
  if(newThis.props.{some-variable} !== prevProps.{some-variable}) {
    getAccounts().then(function(response){
    if(response.status===200){
      newThis.setState({
        Accounts:response.data
      })
    }
  });
 }
}

Adding conditional setState is very important here else you will end up in an infinite loop.

As per the official docs as well:

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition or you'll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you're trying to “mirror” some state to a prop coming from above, consider using the prop directly instead.

Hope it helps.

If you want to render the component again, then change the props from the parent. If props change then child component automatically going to render. And by this features, you can also render the selective component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM