简体   繁体   中英

React Js how can i update the State after changes? With componentDidUpdate?

Hello i've been trying to implement componentDidUpdate. But i have a problem. But i think im doing some part correct, like i have the If statement required? im pretty sure this worked like 2 hours ago but now it's looping in the console. what am i missing?

I will start by posting the most relevant info from my component. I also have CRUD in my component. The view is updating fine after every change but with a downside of a loop from componentDidUpdate that wont stop.

i Would appreciate some help on this matter i've tried to do some research, i guess i should not call the API again? but how can i fix this issue.

i will only post the relevant code from my component.

enter code here

state = { productList: [], statusMsg: "", };

  // READ FROM API
  getDataFromProductsApi() {
    axios
      .get("https://localhost:44366/api/Products/")
      .then((res) => {
        console.log(res.data);
        this.setState({
          productList: res.data,
        });
      })
      .catch((error) => {
        console.log(error);
        this.setState({ statusMsg: "Error retreiving data" });
        if (axios.isCancel(error)) return;
      });
  }

  componentDidMount() {
    this.getDataFromProductsApi();
  }

  // reupdate the state on Changes
  componentDidUpdate(prevProps, prevState) {
    console.warn("changes");
    if (prevState.productList !== this.state.productList) {
      axios.get("https://localhost:44366/api/Products/").then((res) => {
        console.log(res.data);
        this.setState({
          productList: res.data,
        });
      });
    }
  }

//Post axios.post("https://localhost:44366/api/Products/", this.state).then((response) => { console.log(response); this.setState({ statusMessage: "Product Added" }); }).catch((error) => { console.log(error); this.setState({ statusMessage: "Something went wrong" }); if (axios.isCancel(error)) return; }); };

  // DELETE FROM API
  deleteProduct = (productId, productName) => {
    if (window.confirm("Are you sure? you want to delete")) {
      axios
        .delete(`https://localhost:44366/api/Products/${productId}`)
        .then((response) => {
          console.log(response);
          this.setState({
            statusMsg: `Product name: ${productName} With the ID: ${productId} was removed!`,
            //updating state to show the changes in view instantly
            //  productList: this.state.productList.filter(
            //  (item) => item.id !== productId
            //),
          });
        });
    }
  };

Since arrays are objects in JS, two arrays are equal only is they reference the same value(not different instances of that same value).

So using === and !== to compare arrays would be wrong.

console.log([1, 2] === [1, 2])   // returns false

let obj1 = {
    name: 'Disney'
};

let obj2 = {
    name: 'Disney'
}

console.log(obj1 === obj2);    // returns false

console.log([obj1] == [obj2]);  // returns false; 

So, I guess the problem is here in (prevState.productList.== this.state.productList)

You could refer to this answer for more on How to compare arrays in JavaScript?

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