[英]Why is using setState inside componentDidUpdate seen as a bad practice in React?
I need to update a child's state when a prop gets updated, so I made something like this:当道具更新时,我需要更新孩子的状态,所以我做了这样的事情:
componentDidUpdate(prevProps) {
const { searchValue, searchCriterion } = this.props;
if (searchValue !== prevProps.searchValue) {
this.setState({ searchValue });
}
if (searchCriterion !== prevProps.searchCriterion) {
this.setState({ searchCriterion });
}
}
ESLint's airbnb guide is complaining about it and throwing this warning , even though I can't see any noticeable rendering or performance issues. ESLint 的 airbnb 指南正在抱怨它并抛出这个警告,即使我看不到任何明显的渲染或性能问题。
The warning says:警告说:
Updating the state after a component update will trigger a second render() call and can lead to property/layout thrashing.
在组件更新后更新状态将触发第二次 render() 调用,并可能导致属性/布局抖动。
Is there a better way to update a child's state when a prop has a new value?当道具具有新值时,是否有更好的方法来更新孩子的状态?
Or should I ignore the warning?或者我应该忽略警告?
The problem of your code is that it might create an infinite loop.您的代码的问题是它可能会创建一个无限循环。 When you call the
setState
method, you trigger a second render
, just like the warning says, and consequently a new componentDidUpdate
.当您调用
setState
方法时,您会触发第二次render
,就像警告所说的那样,因此会触发一个新的componentDidUpdate
。
In order to solve this problem, you might want to create a break condition for certain values of your state to get out of your loop.为了解决这个问题,您可能希望为状态的某些值创建一个中断条件以退出循环。 For example, you could simply use a flag like so:
例如,您可以简单地使用如下标志:
componentDidUpdate(prevProps) {
const { searchValue, searchCriterion } = this.props;
if (this.state.isAlreadyUpdated === true) {
this.setState({ isAlreadyUpdated: false });
break;
} else {
this.setState({ isAlreadyUpdated: true });
}
if (searchValue !== prevProps.searchValue) {
this.setState({ searchValue });
}
if (searchCriterion !== prevProps.searchCriterion) {
this.setState({ searchValue });
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.