简体   繁体   中英

React js control componentDidUpdate() method

I want to change a API parameter by click function and render new data. When I trigger componentDidUpdate by onclick event listener,the api data changed first and worked fine for first click. But When click second time the api call ran completely. The parameter currentPage is assigned to this.state.count and this this.state.count valued in incremented on click.

My code below:

import React from 'react';    

class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {

      products: [],
      count: 1,      

    };
  }

  componentDidMount() {    
    this.ProductList();  
  }
  componentDidUpdate() {  
    let change = document.getElementById("change");
    change.addEventListener("click",(e)=>{
      this.changeParams();
      this.ProductList();  
    })
  }
  changeParams = (e) =>{
    this.setState({count: this.state.count + 1})
  }       

  ProductList() {
    var myHeaders = new Headers();
    myHeaders.append("Cookie", "PHPSESSID=822cu5ctftcpo8f98ehklem4k9");

    var requestOptions = {
      method: 'GET',
      headers: myHeaders,
      redirect: 'follow'
    };
    fetch("http://192.168.31.236/magento/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=category_id& searchCriteria[filterGroups][0][filters][0][value]=2& searchCriteria[filterGroups][0][filters][0][conditionType]=eq&searchCriteria[sortOrders][0][field]=price& searchCriteria[sortOrders][0][direction]=ASC& searchCriteria[pageSize]=20& searchCriteria[currentPage]="+this.state.count, requestOptions)
      .then(response => response.text())
      .then(result => this.setState({products:result}),)
      .catch(error => console.log('error', error));
    }
  render() {

    const productsList = () =>{
        let pro = [];
          if(typeof this.state.products === 'string') {
            pro = JSON.parse(this.state.products)
            console.log(pro)
          }else{
            pro = []
          }
          if(pro.items && typeof pro.items !== "undefined"){
              return pro.items.map((item, i) => (
                <div>
                  <h1>{ item.name }</h1>
                </div>
              ));
          }           
    }
    return(     
      <div>
        {productsList()}
        <button id="change">Change</button>
      </div>
    );
  }


}

export default App;

Rather than manually attaching event listeners, do it through React. In pretty much most cases you shouldn't be doing DOM operations directly.

class App extends React.Component {
  // ...

  /* You don't need this
  componentDidUpdate() {  
  }
  */

  handleChangeClick = () => {
    this.changeParams();
    this.ProductList();  
  }

  // ...

  render() {
    // ...
    return(     
      <div>
        {productsList()}
        <button id="change" onClick={this.handleChangeClick}>Change</button>
      </div>
    );
  }
}

The reason why your approach doesn't work is because React may be producing and destroying DOM elements in ways you don't expect, so making sure you manually attach and detach event listeners to the right elements is difficult to get right.

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