reactjs中我的componentDidUpdate会发生什么?

问题描述 投票:0回答:3

这是文件app.js

...
constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      inputValue: "",
      currentName: "",
      todoSearch: "",
      idUpdate: "",
      loader: true
    };
  }
 componentDidUpdate(){
    this.setState({
      loader: true
    })
  }
  componentDidMount() {
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then((res) => {
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
...

i在我的应用程序中添加了componentDidUpdate,但它显示消息:已超过最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。

reactjs web redux frontend lifecycle
3个回答
2
投票

componentDidUpdate每次在设置状态发生时调用,因此您必须在didUpdate中删除setState或根据这样的条件进行调用..

componentDidupdate(){
 //check this is called every time when render executed .
 console.log('did update');
  if(some condition){
   this.setState({});
 }
}

0
投票

因此,您正在componentDidUpdate中更新状态中的某些内容,并且更新状态会触发此状态,因此它处于无限循环中,您能解释一下我想做的事情我可以给出解决方案吗?


0
投票

嗨,尝试这种方式以避免最大程度的循环执行。

import React from "react";
import axios from "axios";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      loader: true
    };
  }
  componentDidMount() {
    this.setState({ loader: true });
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then(res => {
        console.log(res.data);
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
  render() {
    const { loader } = this.state;
    return (
      <div>
        {loader
          ? "Loading"
          : this.state.todoLists.map(res => {
              return (
                <ul key={res.id}>
                  <li>{res.id}</li>
                  <li>{res.name}</li>
                </ul>
              );
            })}
      </div>
    );
  }
}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.