首页 > 解决方案 > 超过最大更新深度

问题描述

我收到以下错误(从虚拟服务器收到数据后)

超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制了嵌套更新的数量以防止无限循环。

这是相关代码

class Blog extends Component {
  state = {
    posts: [],
    selectedPostId: null
  }

  componentDidMount () {
    axios.get("https://jsonplaceholder.typicode.com/posts").then(response => {
      const updatedDat = response.data
      const updatedData = []
      for (let i=0; i<5; i++) {
      updatedDat[i].author = "Max";
      updatedDat[i].key = i;
      updatedData.push(updatedDat[i])
    }
      this.setState({posts:updatedData})
    }, function (error) {
    })
  }

  postClicked = (id) => {
    this.setState({selectedPostId: id})
  }
render () {
  const newPosts = this.state.posts.map(el => {
    return <Post key={el.id}
     title={el.title}
     author={el.author}
     clicked={this.postClicked(el.id)}/>
  })

    return (
        <div>
            <section className="Posts">
              {newPosts}
            </section>
            <section>
                <FullPost display={this.state.selectedPostId}/>
            </section>
            <section>
                <NewPost />
            </section>
            </div>
        );
    }
}

export default Blog;

有问题的错误行是

 postClicked = (id) => {
> 30 |   this.setState({selectedPostId: id})
  31 | }

   clicked={this.postClicked(el.id)}/>

clicked 被传递给 onCLick 的子组件

 <article className="Post"  onClick={props.clicked}>

现在,当我做/更改类似的东西时,我可以修复错误

clicked={() => this.postClicked(el.id)}

[问题]:谁能告诉我为什么我首先收到上述错误以及为什么这个(clicked={() => this.postClicked(el.id)})能够修复它。

标签: javascriptreactjs

解决方案


您更改为:

clicked={() => this.postClicked(el.id)})}

解决了您的问题,因为您不是this.postClicked()立即调用该函数,而是创建一个仅在需要时才调用的新函数。


推荐阅读