A.RR
A.RR

Reputation: 21

How to Maximum update depth exceeded in react

I want to render for drag only once, but renders the infinite loops. i'm use The react Dnd method for this project

this warning is Show : 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.

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 Code:

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)

Upvotes: 0

Views: 2665

Answers (1)

Duncan Thacker
Duncan Thacker

Reputation: 5188

The loop occurs in the render method of your Store component, where it

  • calls this.props.chici(itemS.name), which
  • calls your chichiHandler() function, which
  • calls this.setState() on the parent component, which
  • triggers a re-render, which
  • causes Store to re-render, which...

It looks like you want the chichi function to be called when the user hovers over something, in which case you're better off using the onMouseOver prop on the element in question, rather than try to do it with props (see https://reactjs.org/docs/events.html#mouse-events for more info).

In general you should never call setState() from with in a render(), because it tends to cause these sorts of loops.

Upvotes: 1

Related Questions