javascript - Too much recursion when updating state in react -


in example, when try update state during componentdidupdate life cycle callback, too recursion error. how should updating state?

import react 'react';  class notescontainer extends react.component {   constructor(props) {     super(props);     this.state = { listofshoppingitems: [] };   }    componentdidupdate(nextprops, nextstate) {     let newshoppingitems = this.calculateshoppingitems();     this.setstate({ listofshoppingitems: newshoppingitems });   }    calculateshoppingitems() {     let shoppingitemscart = []      if (this.props.milk < 3) {       let value = "buy milk";       shoppingitemscart.push(value);     }      if (this.props.bread < 2) {       let value = "buy bread";       shoppingitemscart.push(value);     }      if (this.props.fruit < 10) {       let value = "buy fruit";       shoppingitemscart.push(value);     }      if (this.props.juice < 2) {       let value = "buy juice";       shoppingitemscart.push(value);     }      if (this.props.sweets < 5) {       let value = "buy sweets";       shoppingitemscart.push(value);     }      return shoppingitemscart;   }    render() {     return (       <div>         etc...       </div>     );   } }  export default notescontainer; 

componentdidupdate triggered when either props or state has changed. if change state in method, causing infinite loop (unless implement shouldcomponentupdate).

it looks state changes when receive new props, therefore componentwillreceiveprops seems place. docs:

invoked when component receiving new props. method not called initial render.

use opportunity react prop transition before render() called updating state using this.setstate(). old props can accessed via this.props. calling this.setstate() within function not trigger additional render.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -