Reputation: 372
The code below will call render() function three times. Is there a way to wait till all the three properties in state will be updated and then call render() only once? Maybe I should use shouldComponentUpdate? I'm new to ReactJS. I don't know how it would look like. Any ideas?
import React from "react";
export default class MyClass extends React.Component {
constructor() {
super();
this.state = {
first: "value1",
second: "value2",
third: "value3"
};
}
changeFirst() {
setTimeout(() => {
this.setState({ first: "somethingFirst" });
}, 2000);
}
changeSecond() {
setTimeout(() => {
this.setState({ second: "somethingSecond" });
}, 3500);
}
changeThird() {
setTimeout(() => {
this.setState({ third: "somethingThird" });
}, 5000);
}
componentDidMount() {
this.changeFirst();
this.changeSecond();
this.changeThird();
}
render() {
return (
<div>
{console.log(this.state.first) +
"\n" +
console.log(this.state.second) +
"\n" +
console.log(this.state.third) +
"\n"}{" "}
</div>
);
}
}
Upvotes: 0
Views: 58
Reputation: 17654
yes you can use shouldcomponentupdate
shouldComponentUpdate(nextProps, nextState){
const { first, second, third } = this.state;
if(first !== nextState.first && second !== nextState.second && third !== nextState.third){
return true;
}
return false;
}
this will prevent the component from updating unless the three state entires are updated.
Upvotes: 2
Reputation: 953
You can simply exit from the render function until all three variables are set:
import React from "react";
export default class MyClass extends React.Component {
constructor() {
super();
this.state = {
first: "",
second: "",
third: ""
};
}
changeFirst() {
setTimeout(() => {
this.setState({ first: "somethingFirst" });
}, 2000);
}
changeSecond() {
setTimeout(() => {
this.setState({ second: "somethingSecond" });
}, 3500);
}
changeThird() {
setTimeout(() => {
this.setState({ third: "somethingThird" });
}, 5000);
}
componentDidMount() {
this.changeFirst();
this.changeSecond();
this.changeThird();
}
render() {
if (!first || !second || !third) return (<div> Loading the vars... </div>)
return (
<div>
{console.log(this.state.first) +
"\n" +
console.log(this.state.second) +
"\n" +
console.log(this.state.third) +
"\n"}{" "}
</div>
);
}
}
Upvotes: 0