javascript - 超过最大更新深度 ReactJs componentDidMount
问题描述
我理解了这个错误,我的 componentDidUpdate 函数正在创建一个无限循环,我不知道如何修复它。我发现了回溯显示给我的两个错误,但我不知道该怎么做。这是提交处理程序函数,它位于主(登录)组件中:
submitHandler = event => {
event.preventDefault();
const {month, day, year} = this.state.data;
this.setState({
loading: true,
error: false,
errors: {},
data: {
...this.state.data,
foundation: `${month} ${day} de ${year}`
}
});
fetch('http://127.0.0.1:8000/logup/',
{
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(this.state.data)
}).then(response => {
this.setState({ loading: false });
if (response.ok) {
console.log('redirect to social nets');
} else {
this.setState({ error: true });
}
return response.json();
}).then(json => {
if (this.state.error) {
this.setState({errors: json}) // The traceback give me error right here
} else {
console.log(json);
}
});
};
我在该登录组件的渲染中也有许多 Inputs 组件,回溯也在这里显示错误。
state = {
error: false
};
componentDidUpdate() {
let bad = Object.keys(this.context.errors).includes(this.props.name);
if (bad) {
this.setState({ error: true }); // traceback give me error too.
};
};
解决方案
在您componentDidUpdate
以下列方式更新状态:
this.setState({ error: true })
您这样做的条件是:
Object.keys(this.context.errors).includes(this.props.name)
设置状态会导致组件重新渲染并更新,因此componentDidUpdate
将再次运行。但是,当这种情况发生时,您的上述条件很可能仍然是正确的。因此,您将再次更新状态,并且 React 不会短路状态更新,因为您每次都在创建一个新对象。在这里拯救自己的一种简单方法是将您的条件更改为:
if (bad && !this.state.error) {
this.setState({ error: true }); // traceback give me error too.
};
推荐阅读
- r - 在R中将2行矩阵变成一行和一列
- string - DejaVu:free():下一个尺寸无效(正常)
- css - bootswatch 中的 CSS 样式不适用于 Shiny R
- mongodb - 这个奇怪的 BSON 日期保存是怎么回事?
- android - 为什么使用接口适配器 Activity 时出现 ClassException?
- environment-variables - 如何在 GitLab Omnibus 配置中使用环境变量
- vb.net - 在表单关闭时关闭特定应用程序
- react-native - 尝试从 expo 中的 react-native-appearance 导入时,Null 不是对象
- amazon-web-services - 不使用 EKS 时,我们可以在 AWS 的 Kubernetes 集群上使用 AWS VPC CNI
- python-3.x - 使用从 txt 文件中的列表中获取的变量写入文件