【发布时间】:2021-03-21 23:37:54
【问题描述】:
我得到了
错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。
但我读到的内容应该可以在 componentDidMount 中调用 setState 而不会出错。
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
matchtedProducts: [],
products: [],
}
}
async componentDidMount() {
try {
const products = await getProducts()
this.setState({ products })
} catch(err) {
console.log(err)
}
}
componentDidUpdate() {
const productColor = this.props.size.trim().toLowerCase()
const productSize = this.props.color.trim().toLowerCase()
const matches = []
this.state.products.map(product => {
const title = product.title
const titleSpliitet = title.split(',')
let color = titleSpliitet[1].trim().toLowerCase()
let size = titleSpliitet[2].trim().toLowerCase()
if(color == productColor && size == productSize) {
matches.push(product)
}
})
this.setState({matchtedProducts: matches})
}
render() {
return (<div></div>)
}
}
【问题讨论】:
-
自从你setState componentUpdates,当组件更新它进入componentDidUpdate函数并再次设置状态。所以有一个无限循环。另一方面 componentDidMount 在开始时只触发一次,因此即使您 setState 也不会让您进入无限循环
-
为什么要更新
componentDidUpdate中的状态?
标签: javascript reactjs setstate react-lifecycle