JavaScript How to mount component only when i change class props react mount component only once

I have a ReactJS project where i get JSON from REST Django host and creating a table with filters for it. I have a Table class :

class MainTable extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      results: []
    };
  }

  componentDidMount(){
    axios.get(this.props.link)
      .then(res => {
        this.setState({results: res.data.results});
    });
  }

  render() {
    return (
      <Table hover striped bordered responsive size="sm">
        <thead>
          <tr>
            <th>Name</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {this.state.results.map(result =>
            <tr key={result.fileId}>
              <td>{result.Name}</td>
              <td>{result.Name}</td>
            </tr>
          )}
        </tbody>
      </Table>
    );
  }
}

And Main where i run all filter classes :

class Main extends React.Component {
  constructor() {
    super();
    this.state = {
      origin: '',
      limit: 10
    };

    this.handleChangeOrigin = this.handleChangeOrigin.bind(this);
    this.handleChangeLimit = this.handleChangeLimit.bind(this);
  }

  handleChangeLimit(event) {
    this.setState({limit: event.target.value});
  }
  handleChangeOrigin(event) {
    this.setState({origin: event.target.value});
  }

  render() {
    var link = `http://106.120.89.142:8000/database/?limit=${this.state.limit}&`;
    if (this.state.origin){
      link += `ORIGIN=${this.state.origin.toLowerCase()}`;
      console.log(link)
    }
    return (
      <div>
        <div>
          <h1 className="jumbotron-heading display-4">Here u got database *_*</h1>
        </div>
        <div>
          <Limit handleChange = {this.handleChangeLimit} />
        </div>
        <div>
          <OriginRow handleChange = {this.handleChangeOrigin} />
        </div>
        <div id="tableWrapper">
          <MainTable link={link} />
        </div>
      </div>
    );
  }
}

And i have a problem with it, cause when i use componentDidMount(), my axios.get(my link to REST JSON) runs only once. When i use axios in Table class render(), it hits my server few times per second. Can i make mounting only when my props to Table class changed?

Answer:1

You should take a look at the shouldComponentUpdate() life-cycle method, here.

shouldComponentUpdate()

shouldComponentUpdate(nextProps, nextState)

Use shouldComponentUpdate() to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.


Add the following snippet to your MainTable component. This will prevent it from re-rendering, unless the props have changed.

shouldComponentUpdate(nextProps) {
  return JSON.stringify(this.props) !== JSON.stringify(nextProps);
}

this will check for all props. If you want to check against a specific prop, you can do:

shouldComponentUpdate(nextProps) {
  return JSON.stringify(this.props.link) !== JSON.stringify(nextProps.link);
}

As pointed out in the comments, there is always a small chance that JSON.stringify(this.props) !== JSON.stringify(nextProps) will return false even when they are equal.

As such, if you want a more robust way of comparing the this.props object to the newProps object, you should take a look at this post.

Answer:2

As pointed out you can implement shouldComponentUpdate. Alternatively if you dont need a deep comparison, ie on any collections or objects, just use PureComponent instead of Component:

https://github.com/facebook/react/blob/master/docs/docs/reference-react.md

React.PureComponent# React.PureComponent is exactly like React.Component but implements shouldComponentUpdate() with a shallow prop and state comparison.

Answer:3

I am trying to change the icon on collapse and facing an event firing issue The HTML <div id="collapse-menu" class="row"> <div class=" panel"> <a href="#...

I am trying to change the icon on collapse and facing an event firing issue The HTML <div id="collapse-menu" class="row"> <div class=" panel"> <a href="#...

  1. bootstrap collapse event handler
  2. bootstrap collapse event not firing
  3. bootstrap collapse event angular
  4. bootstrap collapse event listener
  5. bootstrap collapse event
  6. bootstrap collapse event example
  7. bootstrap collapse event not working
  8. bootstrap collapse event get element
  9. bootstrap collapse event show
  10. bootstrap 4 collapse event
  11. bootstrap 3 collapse event
  12. bootstrap panel collapse event
  13. bootstrap accordion collapse event
  14. bootstrap collapse click event
  15. bootstrap navbar collapse event
  16. bootstrap collapse javascript event
  17. bootstrap after collapse event
  18. bootstrap collapse open event
  19. bootstrap data-toggle collapse event
  20. vue bootstrap collapse event

I want to get all selected values of bootstrap-multiselect on button click. My JSP page code is given below <script type="text/javascript"> $(document).ready(function() { $('#...

I want to get all selected values of bootstrap-multiselect on button click. My JSP page code is given below <script type="text/javascript"> $(document).ready(function() { $('#...

  1. javascript bootstrap multiselect
  2. javascript multiselect bootstrap
  3. js bootstrap multiselect
  4. vue js bootstrap multiselect
  5. js/bootstrap-multiselect.js download
  6. js/bootstrap-multiselect.js cdn
  7. angularjs bootstrap multiselect
  8. angularjs bootstrap multiselect dropdown

I have an attribute that is of string data type.I am using the algoliasearchHelper object to search through my Algolia database. What I want to do is create a facet filter that takes a specified ...

I have an attribute that is of string data type.I am using the algoliasearchHelper object to search through my Algolia database. What I want to do is create a facet filter that takes a specified ...

Sample: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Dynamic Link</title> </head> <body> <input type="text" value="http:...

Sample: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Dynamic Link</title> </head> <body> <input type="text" value="http:...