Динамически создаваемый массив с помощью html-объектов - асинхронный - PullRequest
0 голосов
/ 10 июля 2019

Мне нужно вывести массив объектов HTML. Моя функция, которая обрабатывает вывод, работает асинхронно. Я понимаю, что в асинхронном программировании последний элемент отображается только в цикле.

Мои попытки заключались в переносе кода в другие замыкания, но он ничего не выводил.

let run = () => {
  let array1 = [];
  for (let j = 0; j < 20; j++) {
    let children1 = [];
    for (let i = 0; i < 20; i++) {
      for (var k = 0; k < coordinate.length; k++) {
        let kk = k;
        setTimeout(function () {
          if (i === coordinate[kk].x && j === coordinate[kk].y) {
            children1.push(<Pool key={`${i}${j}`} row={`${square2}`}/>);
          }
          else if(i===packageCoordinate.x && j===packageCoordinate.y){
            children1.push(<Pool key={`${i}${j}`} row={`${square3}`}/>);
          }
          else{
            children1.push(<Pool key={`${i}${j}`} row={`${square1}`}/>);
          }
        }, 1000);
      }
    }
    array1.push(<div key={`${j}`}>{children1}</div>);
  }
};

По моему мнению, если государственные деятели не будут вызваны должным образом.

EDIT: Я хочу сделать, если заявление динамически, но k всегда равно 0. И проблема с ошибками: я получаю сообщение об ошибке:

Uncaught SyntaxError: Неожиданный токен c в JSON в позиции 0

 export default class Board extends React.Component {

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

renderMainArray(){
    return this.state.mainArray;
}
/////////////////////////////////////////////////////////////////
stop = () => {
    alert("GAME OVER");
    window.location.reload("index.html");
}
run = () => {   
        let help="";
        let array1=[];
        for(let j=0;j<20;j++){

            let children1=[];
            for(let i=0;i<20;i++){                  
                help="";
                console.log(j);
                for(let k=0;k<coordinate.length;k++){
                    help+="coordinate[k].x===i && coordinate[k].y===j ";

                    if(k!==coordinate.length-1){
                        help+="||";
                    }
                }   

                    if(JSON.parse(help)){
                        children1.push(<Pool key={`${i}${j}`} row={`${square2}`}/>);
                    }   
                    else if(i===packageCoordinate.x && j===packageCoordinate.y){
                        children1.push(<Pool key={`${i}${j}`} row={`${square3}`}/>);
                    }
                    else{
                        children1.push(<Pool key={`${i}${j}`} row={`${square1}`}/>);
                    }
                }
            array1.push(<div key={`${j}`}>{children1}</div>);
            }   


        /////////////////////////////////////////////////////////////////////////////////////////
        console.log(help);
        if(up===true){
        let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.x--;
        coordinate[coordinate.length-1]=Object.assign({}, help);
        }

        if(down===true){
        let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.x++;
        coordinate[coordinate.length-1]=Object.assign({}, help);

        }

        if(right===true){
        let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.y++;
        coordinate[coordinate.length-1]=Object.assign({}, help);
        }

        if(left===true){
            let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.y--;
        coordinate[coordinate.length-1]=Object.assign({}, help);
        }

        /////////////////////////////////////////////////////////////////////////////////////////
        if(coordinate[coordinate.length-1].x>20 || coordinate[coordinate.length-1].x<(-1) || coordinate[coordinate.length-1].y>20 || coordinate[coordinate.length-1].y<(-1) ){
            this.stop();
        }
        ////////////////////////////////////////////////////////////////////////////////////////
        this.setState({mainArray: array1});

    }
///////////////////////////////////////////////////


render() {
    return (        
        <div  className="main"> 
        {this.renderMainArray()}
        <button onClick={() => {setInterval(this.run, 1000);}}>Start the game!</button>
        </div>
    );
}

}

1 Ответ

0 голосов
/ 11 июля 2019

Модифицировано и работает правильно.Я изменил способ итерации внутреннего цикла - JSON.parse и JSON.stringify

run = () => {   
        let help="";
        let array1=[];
        for(let j=0;j<20;j++){

            let children1=[];
            for(let i=0;i<20;i++){                  
                help="";
                let jsonData = JSON.parse(JSON.stringify(coordinate));  //HERE
                for(let k=0;k<jsonData.length;k++){   /////HERE
                    let myObject = jsonData[k];       /////////////AND HERE
                    help+=`${myObject.x}===${i} && ${myObject.y}===${j} `;
                    if(k!==(jsonData.length-1)){
                        help+="||"
                    }
                }
                    if(eval(help)){
                        children1.push(<Pool key={`${i}${j}`} row={`${square2}`}/>);
                    }   
                    else if(i===packageCoordinate.x && j===packageCoordinate.y){
                        children1.push(<Pool key={`${i}${j}`} row={`${square3}`}/>);
                    }
                    else{
                        children1.push(<Pool key={`${i}${j}`} row={`${square1}`}/>);
                    }


            }
            array1.push(<div key={`${j}`}>{children1}</div>);
        }   


        /////////////////////////////////////////////////////////////////////////////////////////
        console.log(help);
        if(up===true){
        let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.x--;
        coordinate[coordinate.length-1]=Object.assign({}, help);
        }

        if(down===true){
        let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.x++;
        coordinate[coordinate.length-1]=Object.assign({}, help);

        }

        if(right===true){
        let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.y++;
        coordinate[coordinate.length-1]=Object.assign({}, help);
        }

        if(left===true){
            let help=Object.assign(coordinate[coordinate.length-1]);
            for(let i=0;i<=coordinate.length-2;++i){
                coordinate[i]=Object.assign({}, coordinate[i+1]);
            }
        help.y--;
        coordinate[coordinate.length-1]=Object.assign({}, help);
        }

        /////////////////////////////////////////////////////////////////////////////////////////
        if(coordinate[coordinate.length-1].x>20 || coordinate[coordinate.length-1].x<(-1) || coordinate[coordinate.length-1].y>20 || coordinate[coordinate.length-1].y<(-1) ){
            this.stop();
        }
        ////////////////////////////////////////////////////////////////////////////////////////
        this.setState({mainArray: array1});

    }
///////////////////////////////////////////////////


render() {
    return (        
        <div  className="main"> 
        {this.renderMainArray()}
        <button onClick={() => {setInterval(this.run, 400);}}>Start the game!</button>
        </div>
    );
}
...