lundi 27 mai 2019

Code is executing twice but it should run once only?

My code is executing twice the componentWillMount() method is executing twice.

tried using different life cycles methods as well.

import React from "React"; import ProductDetails from "./ProductDetails";

class Product extends React.Component { constructor(props) { super(props); this.state={ data : null }
} componentWillMount() { console.log("before"); let xhr = new XMLHttpRequest(); xhr.onreadystatechange = ()=>{

    if(xhr.readyState === 4 && xhr.status === 200)
    {
      let dataRecived = JSON.parse(xhr.responseText);
      this.setState({data: dataRecived})
    }

  }
  xhr.open("GET", "./db.json", true);
  xhr.send();
  console.log("before",this.state.data);
}

render(){
  console.log("after",this.state.data)
  return(
  <div>
    {/* <ProductDetails  data={this.state.data}/> */}
  </div>
  );
}

}

export default Product;

It should executes once only




Aucun commentaire:

Enregistrer un commentaire