Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  116] [ 1]  / answers: 1 / hits: 15753  / 7 Years ago, mon, april 10, 2017, 12:00:00

I'm playing around with React and I am getting the functionality I want but it is extremely slow due to an infinite loop somewhere. I believe it's in the component lifecycle methods but I'm not sure how to reformat the below code to have the same functionality but without the infinite loop. Any advice on best practices would be appreciated.



class App extends Component {
constructor() {
super();
this.state = {
num: 13,
num2: 10,
total: 0
}
}

componentDidMount() {
this.addNums();
}

componentDidUpdate() {
this.addNums();
}

addNums(){
var added = parseInt(this.state.num) + parseInt(this.state.num2);
this.setState({total: parseInt(added)});
}

change(num) {
this.setState({num: num});
console.log(this.state);
}
change2(num2) {
this.setState({num2: num2});
console.log(this.state);
}

render(){
return (
<div>
<TopBar />
<Combinatoric test={this.state.num} changeNumber={this.change.bind(this)}/>
<Combinatoric test={this.state.num2} changeNumber={this.change2.bind(this)}/>
<h2>Total: {this.state.total}</h2>
<h1>hello world</h1>
</div>
);
}
}

More From » reactjs

 Answers
2

The infinite loop happends because you call this.addNums() in the componentDidUpdate lifecycle function. addNums sets the state which causes a componentUpdate and hence ComponentDidUpdate is called again and hence the loop continues.



You can remove this function and since num and num2 are there in the state and total can then just be caluculated in the render based on num and num2



class App extends Component {
constructor() {
super();
this.state = {
num: 13,
num2: 10,
total: 0
}
}


change(num) {
this.setState({num: num});
console.log(this.state);
}
change2(num2) {
this.setState({num2: num2});
console.log(this.state);
}

render(){
var total = parseInt(this.state.num) + parseInt(this.state.num2);
return (
<div>
<TopBar />
<Combinatoric test={this.state.num} changeNumber={this.change.bind(this)}/>
<Combinatoric test={this.state.num2} changeNumber={this.change2.bind(this)}/>
<h2>Total: {total}</h2>
<h1>hello world</h1>
</div>
);
}
}

[#58212] Friday, April 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
lucianod questions
;