setState secound参数回调函数不起作用



我的问题依赖于我无法调用SetState React函数的第二个参数。

我确实知道它是异步的功能,它有自己的规则,但有问题,我被困在这里

constructor(props){
    super(props);
    this.state = {
        mainArray: []
    };
    let array=[];
    for(let i=0;i<20;i++){
        let children=[];
        for(let j=0;j<20;j++){
            children.push(<Pool key={`${i}${j}`} row={`${square1}`}/>);
        }   
    array.push(<div key={`${i}`}>{children}</div>);     
    }
    this.setState({mainArray: array},function (){console.log('message');}); 
    console.log(this.state.mainArray);
}

该消息未在控制台中显示,最后一行确实仅显示空数组

问题可能是在构造函数中调用setStatesetState触发构造函数已经是一部分的组件的生命周期。所以也许您正在与生命周期混乱。

当您在componentDidMount中称为setState时会发生什么?

另外,在构造中,您不需要SetState 。在构造函数中,仅在构造函数中,您可以直接编写状态:

constructor(props){
    super(props);
    const array = [];
    for(const i = 0; i < 20; i++){
        let children = [];
        for(let j = 0; j < 20; j++){
            children.push(<Pool key={`${i}${j}`} row={`${square1}`}/>);
        }   
        array.push(<div key={`${i}`}>{children}</div>);     
    }
    this.state = { mainArray: array };
    console.log(this.state.mainArray);
}

最新更新