What I'm trying to do is set up a timer that every 3 seconds adds a new component to the page. Everything is fine until the third second, where the app crashes with:
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Is there anyway I could fix this or does someone have a better solution for doing this? Here's the code:
class Test extends Component {
constructor(props) {
super(props);
this.state = {
time: 0,
colors: []
}
this.create = this.create.bind(this);
}
componentDidMount() {
this.timer = setInterval(() => {
this.setState({time: this.state.time + 1});
}, 1000);
}
componentDidUpdate(prevProps, prevState) {
if (this.state.time % 3 === 0) {
if (prevState.colors !== this.state.colors) {
this.create()
}
}
}
create() {
let colors=['blue', 'green', 'red'];
let randomNum = Math.floor(Math.random() * 3);
let newColors = this.state.colors;
newColors.push({color: colors[randomNum], num: randomNum});
this.setState({colors: newColors});
}
render() {
return (
<div>
<h1>{this.state.time}</h1>
{this.state.colors.map(item => (
<Random color={item.color} num={item.num} />
))}
<button onClick={this.create}></button>
</div>
)
}
}
export default Test;
What I'm trying to do is set up a timer that every 3 seconds adds a new component to the page. Everything is fine until the third second, where the app crashes with:
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Is there anyway I could fix this or does someone have a better solution for doing this? Here's the code:
class Test extends Component {
constructor(props) {
super(props);
this.state = {
time: 0,
colors: []
}
this.create = this.create.bind(this);
}
componentDidMount() {
this.timer = setInterval(() => {
this.setState({time: this.state.time + 1});
}, 1000);
}
componentDidUpdate(prevProps, prevState) {
if (this.state.time % 3 === 0) {
if (prevState.colors !== this.state.colors) {
this.create()
}
}
}
create() {
let colors=['blue', 'green', 'red'];
let randomNum = Math.floor(Math.random() * 3);
let newColors = this.state.colors;
newColors.push({color: colors[randomNum], num: randomNum});
this.setState({colors: newColors});
}
render() {
return (
<div>
<h1>{this.state.time}</h1>
{this.state.colors.map(item => (
<Random color={item.color} num={item.num} />
))}
<button onClick={this.create}></button>
</div>
)
}
}
export default Test;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.