gpt4 book ai didi

javascript - React setState inside componentDidUpdare 导致超出最大更新深度

转载 作者:行者123 更新时间:2023-12-05 09:07:14 24 4
gpt4 key购买 nike

我得到了

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

但根据我的阅读,我应该能够在 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 都会触发渲染,然后再次触发 componentDidMount,这基本上会导致无限循环。要停止该循环,您需要设置一些条件,以防止再次渲染,例如

    componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}

关于javascript - React setState inside componentDidUpdare 导致超出最大更新深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65236366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com