我只想渲染一次拖动,但渲染无限循环。 我在这个项目中使用了 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)
最佳答案
循环发生在 Store
组件的 render 方法中
- 调用
this.props.chici(itemS.name)
,其中 - 调用您的
chichiHandler()
函数, - 在父组件上调用
this.setState()
,这 - 触发重新渲染,这
- 导致
Store
重新渲染,这...
看起来您希望当用户将鼠标悬停在某物上时调用 chichi
函数,在这种情况下,您最好在元素上使用 onMouseOver
属性有问题,而不是尝试使用 props 来做到这一点(有关更多信息,请参阅 https://reactjs.org/docs/events.html#mouse-events)。
一般来说,您不应该在 render()
中调用 setState()
,因为它往往会导致此类循环.
关于javascript - 如何在 react 中超出最大更新深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54402638/