componentDidupdate setState reactjs无限循环



即使有很多问题有相同的主题行,我也找不到答案。

问题

我有一个选择的下拉。单击其中,我调用一个API,该API获取一些键值。我认为这组钥匙值输入字段是组件。因此,每当我选择的下拉列表的选择时,我都使用生命周期方法来处理API调用。另外,我记录了这些输入键值,并将其状态发送回父组件。

根据ReactJS生命周期方法:

我使用

componentDidmount 初始渲染后首次致电API。这有效。

componentDidupdate 致电API以获取后续的API调用,以选择选定的下拉更改。但这是问题。当我尝试更新输入字段时,程序会落入无限循环,因此有无限的API调用。在调试问题后,我很确定问题是SetState(),但是我找不到在componentDidupdate方法中处理状态的最佳方法。

此链接完全复制了我的问题,但我想要一个标准化的解决方案

希望这很清楚。感谢提前的帮助!

在文档中很清楚地阐明了这一点:

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

可以在ComponentDidupDate()中立即调用SetState(),但请注意 它必须包裹在上面示例中的条件中,或 您将导致无限循环。

您可以在componentDidUpdate()中使用setState()。但是您必须为此使用条件。否则,它会获得无限的循环。

作为示例,

 componentDidUpdate(){
    if(this.props.id !== this.state.id) {
        this.setState({
            id: this.props.id 
        });
    }
 }

发生这种情况,因为setState触发了对componentDidupdate的调用。

当调用ComponentDidupdate时,SetState不会检查状态更改是否发生。它只会一次又一次地调用componentDidupdate,从而导致stackoverflow。

  class Component extends React.Component{
    constructor(props){
      super(props);
      this.state = {changeState: false}
    }
    componentDidMount(){
      this.setState({changeState: true});
    }
    componentDidUpdate(){
        this.setState({changeState: false});
    } 
 }

在这里,第一个变化设置为构造器中的false,然后触发了componentDidmount,将变化状态设置为true。此状态更改触发了componentDidupdate,该状态再次将变化状态设置为true。这一次又一次触发componentDidupdate。

您必须检查两个状态对象之间的实际差异。在下面,您可以找到我的解决方案,我的状态对象具有电影,这是一系列对象。我编辑和电影,然后比较这两个阵列。

    async componentDidUpdate(prevProps, prevState) {
        if (prevState.movies.filter (e => this.state.movies.includes(e))) {
        const response = await axios.get("http://localhost:3002/movies");
        this.setState({ movies: response.data })
    }
}

是的,您不能在componentdidupdate中setState()它导致无限循环。

最新更新