在 componentDidUpdare 中 React setState 导致超出最大更新深度

sha*_*_00 2 javascript setstate reactjs react-lifecycle

我正进入(状态

错误:超出最大更新深度。当组件在 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>)
}
Run Code Online (Sandbox Code Playgroud)

}

avi*_*oni 5

发生这种情况是因为每个 setState 都会触发一次渲染,然后再次触发一次 componentDidMount,这基本上会导致无限循环。要停止该循环,您需要设置一些条件,以防止再次渲染,例如

    componentDidUpdate(previousProps, previousState) {
    if (previousProps.data !== this.props.data) {
        this.setState({/*....*/})
    }
   }
Run Code Online (Sandbox Code Playgroud)