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 usingthis.setstate()
. old props can accessed via this.props. callingthis.setstate()
within function not trigger additional render.
Comments
Post a Comment