Javascript ReactJS-如何在componentDidUpdate中设置状态?

Javascript ReactJS-如何在componentDidUpdate中设置状态?,javascript,html,reactjs,web,jsx,Javascript,Html,Reactjs,Web,Jsx,我想做的是设置一个计时器,每3秒钟向页面添加一个新组件。直到第三秒,应用程序崩溃时,一切正常: 错误:超过最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量,以防止无限循环。 不管怎样,我可以解决这个问题,还是有人有更好的解决方案?代码如下: class Test extends Component { constructor(props) { s

我想做的是设置一个计时器,每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;
类测试扩展组件{
建造师(道具){
超级(道具);
此.state={
时间:0,,
颜色:[]
}
this.create=this.create.bind(this);
}
componentDidMount(){
this.timer=setInterval(()=>{
this.setState({time:this.state.time+1});
}, 1000);
}
componentDidUpdate(prevProps、prevState){
如果(this.state.time%3==0){
if(prevState.colors!==this.state.colors){
这个。create()
}
}
}
创建(){
让颜色=[‘蓝色’、‘绿色’、‘红色’];
让randomNum=Math.floor(Math.random()*3);
让newColors=this.state.colors;
push({color:colors[randomNum],num:randomNum});
this.setState({colors:newColors});
}
render(){
返回(
{this.state.time}
{this.state.colors.map(项=>(
))}
) 
}
}
导出默认测试;
可能是在componentDidUpdate中,您应该使用映射功能来显示这些颜色


不要添加代码图片,自己添加实际代码,尝试发布代码而不是屏幕截图。此外,
this.state.colors
是一个数组,因此不应该对其使用相等运算符。数组是通过引用存储的,因此
console.log([]=[])-->false
。这也意味着您不应该将
newColors
设置为等于它,然后调用
。在它上按
,因为这也会改变反应状态本身,这是一个很大的“否”。您需要对以前的状态数组和当前状态数组之间的元素进行比较。感谢Jayce444的建议,我没有比较阵列,而是以秒为单位比较了以前的状态和当前状态,这是有效的。