【问题标题】:How to Maximum update depth exceeded in react如何在反应中超过最大更新深度
【发布时间】:2019-06-21 11:51:02
【问题描述】:

我只想渲染一次拖动,但渲染无限循环。 我正在为这个项目使用 React Dnd 方法

此警告是显示:超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

chichihandler = (id) => {
    console.log('inApp', id);
    this.setState({
        hoverdID: 123
    })
    console.log("hoverd", this.state.hoverdID)
}
render() {
    return (
        <div className="all">
            <Header />
            <div className='Products_list'  >
                {this.state.productData.map((item) => (
                    <Products key={item.id} item={item} handleDrop={(productId) => this.addItem(productId)} />
                ))}
            </div>
            <div className='Store_list' >
                <div className="storeName" >Store Name</div>
                {this.state.storeData.map((itemS) => (
                    <Store key={itemS.code} itemS={itemS} chichi={(id) => this.chichihandler(id)} />
                ))}
            </div>
        </div>
    )
}

storeData代码:

import React, { Component } from 'react'
import { DropTarget } from 'react-dnd'
function collect(connect, monitor) {
    return {
        connectDropTarget: connect.dropTarget(),
        hovered: monitor.isOver(),
        item: monitor.getItem()
    }
}
class Store extends Component {
    render() {
        const { connectDropTarget, hovered, itemS } = this.props
        const backcgroundColor = hovered ? 'lightgreen' : ''
        if (hovered) {
            this.props.chichi(itemS.name)
            console.log(itemS.name)
        }
        return connectDropTarget(
            <div>
                <div id={itemS.code} className='Store' style={{ background: backcgroundColor }}>
                    {this.props.itemS.name}
                </div>
            </div>
        )
    }
}

export default DropTarget('item', {}, collect)(Store)

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    循环发生在你的Store组件的render方法中

    • 调用this.props.chici(itemS.name)
    • 调用您的chichiHandler() 函数,该函数
    • 在父组件上调用this.setState()
    • 触发重新渲染,
    • 导致Store 重新渲染,这...

    您似乎希望在用户将鼠标悬停在某物上时调用 chichi 函数,在这种情况下,您最好在相关元素上使用 onMouseOver 属性,而不是尝试使用道具(请参阅https://reactjs.org/docs/events.html#mouse-events 了解更多信息)。

    一般情况下,您应该永远render() 中调用 setState(),因为它往往会导致此类循环。

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 2019-02-14
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2020-01-11
      • 1970-01-01
      • 2021-03-21
      相关资源
      最近更新 更多