javascript - 超过最大更新深度
问题描述
我收到以下错误(从虚拟服务器收到数据后)
超过最大更新深度。当组件在 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)}
)能够修复它。
解决方案
您更改为:
clicked={() => this.postClicked(el.id)})}
解决了您的问题,因为您不是this.postClicked()
立即调用该函数,而是创建一个仅在需要时才调用的新函数。
推荐阅读
- php - webhook woocommerce 通过 php 到 mysql
- postgresql - PostgreSQL - 根据字段的值将表上的删除/更新限制为特定角色
- postgresql - 重复 PostgreSQL 错误代码名称 'string_data_right_truncation'
- ruby-on-rails - WebKit/Chrome 时间戳转换为 Ruby/Rails
- docker - Dockerfile ~ 添加 Windows 文件夹的正确语法
- java - ORACLE 报告:REP-1814:报告无法格式化。对象垂直无法放入位置 B_15
- laravel - Laravel - 没有这个框架直接访问 PHP
- windows - Gzip使用批处理和7zip将带有子文件夹的多个文件压缩到每个名称中
- java - 泛型对象参数的类型问题
- android - kotlin 中的 DateFormat 在不同的设备中给出不同的输出