[英]ReactJS - How to setstate within componentDidUpdate?
我想要做的是设置一个计时器,每 3 秒向页面添加一个新组件。 一切都很好,直到第三秒,应用程序崩溃:
错误:超出最大更新深度。 当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况。 React 限制嵌套更新的数量以防止无限循环。
无论如何我可以解决这个问题,或者有人有更好的解决方案吗? 这是代码:
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;
我想要做的是设置一个计时器,每 3 秒向页面添加一个新组件。 一切都很好,直到第三秒,应用程序崩溃:
错误:超出最大更新深度。 当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况。 React 限制嵌套更新的数量以防止无限循环。
无论如何我可以解决这个问题,或者有人有更好的解决方案吗? 这是代码:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.