G
G
gooseNjuice()2018-03-23 09:35:11
JavaScript
gooseNjuice(), 2018-03-23 09:35:11

Unexpected result of a function call. What am I doing wrong?

Problem: When the addEducationDiv function is called, removeEducationDiv is called, and an infinite number of times

class SeekerRegistration extends Component {
    constructor(props) {
        super(props)
        this.state = {
            educations: [({section: Education})],
            ...
        }
        this.addEducationDiv = this.addEducationDiv.bind(this);
        this.removeEducationDiv = this.removeEducationDiv.bind(this);
    }

addEducationDiv() {
    const educations = [...this.state.educations, {section: Education}]
    this.setState({educations});
}

removeEducationDiv({id}) {
    console.log('removing...')
    const educations = this.state.educations.filter(div => div.id !== id)
    this.setState({educations})
}

render() {
    const {addEducationDiv, removeEducationDiv} = this
    const {educations} = this.state
    return <div>
        {educations.map((n, i) =>
            <div><Education id={n.id}/>
                {(i === educations.length - 1) ?
                    <AddButton addSection={addEducationDiv}/> :
                    <RemoveButton removeSection={removeEducationDiv(i)}/>}
            </div>)}
    </div>
}}

Button codes are simple:
const AddButton = ({addSection = f => f}) =>
    <button onClick={addSection}>+</button>
const RemoveButton = ({removeSection = f => f, id}) =>
    <button onClick={removeSection(id)}>-</button>

Why when I click on the AddButton button, an event occurs repeatedly that is not even attached to it? At the same time, after about a thousand calls to removeEducationDiv, addEducationDiv still occurs, that is, the event is added. Then, of course, the message "Maximum update depth exceeded" pops up.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2018-03-23
@gooseNjuice

Now you immediately call removeEducationDiv in the render without waiting for any clicks (you also pass the wrong argument there). It should be like this:
Well, the same error occurs in the RemoveButton component (no arguments are needed at all).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question