jeudi 8 août 2019

Should i use cloned props or change props one time and make the prop into a state

I have something similar to a UIManager and a Form, i receive a fairly big JSON as props of this component, i have to iterate over this JSON and assign a onChangeFunction to each element of this JSON and then render the children using this new JSON, i will also hold the data for all the children in a state using a something like formData=[{ID:Value}] and i also update the said JSON in render using this formData so the value of children are good to go (a two way binding).
Right now i am doing this:

render () {
    let newElementList = deepClone(props.elementList)

    newElementList.forEach(element => {
      if (!element.onChange) {
        element.onChange = this.onElementChange();
      }
    })

    //use newElementList from now on
}

And i was wondering if i should do this instead:

componentDidMount() {
    let newElementList = deepClone(props.elementList)

    newElementList.forEach(element => {
      if (!element.onChange) {
        element.onChange = this.onElementChange();
      }
    })

    this.setState({elementList: newElementList});
}

render () 
{
    //use this.state.elementList from now on
}

Which is the better solution ?
Note i also do some other changes to this JSON for example i update the value parameter for each element which changes and update the JSON.

Aucun commentaire:

Enregistrer un commentaire