[英]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.