首页 > 解决方案 > componentWillUpdate 被无限调用,即使有条件

问题描述

我有一个名为ListOfItems.js的类组件,它列出了一堆对象,如下所示:

class ListOfItems extends Component {
  construction (props) {
    super(props);
    this.state = {
      objectList: []
    }
  }
}

// This gets the list of objects to display
componentDidMount() {
   this.getObjectList();
}

componentDidUpdate(_prevProps, prevState) {

  if( this.state.ObjectList !== prevState.ObjectList) {

     // this is called infinitely
     console.log("entered");
     this.getObjectList();
  }
}

getObjectList = () => {
  const input = { id_for_this_list: id }

  fetch( connectToApi, {
     method: "PUT",
     headers: { //stuff}
     body: JSON.stringify(input)
  })
     .then(res => //)
     .then(result => //)
     .catch(err=>{console.error(err)});
}
     

Object.js(ListOfItems 中显示的每个对象的文件)内部,我有一个删除功能,如果用户选择对象上的“x”图标,该对象将从列表中删除。ListOfItems.js 中的 Object.js 实例如下所示:

{this.state.objectList.map(item) => {
  <Object 
    objectList={this.objectList}
    data={item}
    //few other props here
  >
}

一旦我输入这个 ListOfItems.js,componentWillUpdate 就会被无限调用,即使是有条件的。我希望它只被调用一次——当用户在 ListOfItems 页面上删除一个对象时。

标签: javascriptreactjsinfinite-loopreact-class-based-component

解决方案


推荐阅读