Поместите 2D-массив как объект в переменную состояния

Я пытаюсь реализовать крестики-нолики в React Native. Чтобы получить доступ к предыдущим ходам, я создал состояние, называемое историей, и добавил первое состояние в виде двумерного массива. Я хочу передать {gameState:history[i]} в функцию, чтобы установить this.setState(gameState:history[i]) в функции onTilePress(). Я не могу получить доступ к массиву в onGoPress( ). Прилагаю использованный код. пожалуйста помоги. Заранее спасибо.

import React , {Component} from 'react';
import { StyleSheet, Text, View,TouchableOpacity,Alert,Button,ScrollView } from 'react-native';
import {MaterialCommunityIcons as Icon} from 'react-native-vector-icons'
// import { render } from 'react-dom';


export default class App extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      gameState:[
        [0,0,0],
        [0,0,0],
        [0,0,0]
  
      ],
      currentPlayer: 1,
      
          history: [
              [0,0,0],
              [0,0,0],
              [0,0,0]
        
            ],
          
        };

    }

  componentDidMount(){
    this.initializeGame();
  }

  initializeGame=()=>{
    this.setState({gameState:
    [
      [0,0,0],
      [0,0,0],
      [0,0,0]

    ],currentPlayer:1,
 });
 
  }

  onGoPress=()=>{
    this.setState(gameState:history)
  }

  onNewGamePress=()=>{
    this.initializeGame();
  }

  getWinner=()=>{
     var num_tiles =3;
     var arr=this.state.gameState;
     var sum;
     let i;
     for( i=0;i<num_tiles;i++){
       sum=arr[i][0]+arr[i][1]+arr[i][2];
        if (sum===3){
          return 1;
        }
        else if (sum===-3){
          return -1;
        }
      }

      for(i=0;i<num_tiles;i++){
        sum=arr[0][i]+arr[1][i]+arr[2][i];
         if (sum===3){
           return 1;
         }
         else if (sum===-3){
           return -1;
         }
       }

       sum=arr[0][0]+arr[1][1]+arr[2][2];
       if (sum===3){
        return 1;
      }
      else if (sum===-3){
        return -1;
      }

      sum=arr[0][2]+arr[1][1]+arr[2][0];
       if (sum===3){
        return 1;
      }
      else if (sum===-3){
        return -1;
      }

      return 0;

  }

   onTilePress=(row,col)=> {
      var currentPlayer= this.state.currentPlayer;
      
      var value=this.state.gameState[row][col];
      if (value!==0){
        return;
      }

      var arr=this.state.gameState.slice();
      arr[row][col]= currentPlayer;
      this.setState(prevState => ({
        history: [...prevState.history, {arr}]
      }))

      this.setState({gameState :arr});
      var nextPlayer=(currentPlayer==1)?-1:1
      this.setState({currentPlayer:nextPlayer});

      var winner=this.getWinner();
      if (winner===1){
        Alert.alert("Player X is the winner");
        this.initializeGame();
      }
      else if (winner===-1){
        Alert.alert("Player O is the winner");
        this.initializeGame();
      }
   }

  renderIcon=(row,col)=>{
    var value=this.state.gameState[row][col];
    switch(value)
    {
      case 1:return <Icon name = "close" style = {styles.tileX}/> 
      case -1:return <Icon name = "circle-outline" style = {styles.tileO}/>
      default:return <View />
    }
  }


  render(){
    
  return (
    <ScrollView style = {{marginTop:50}}>
    <View style = {styles.container}>
    <Text style = {{fontSize:60, fontStyle:'italic',paddingBottom:30}}>TIC TAC TOE</Text>
      <View style = {{flexDirection:'row'}} >
        <TouchableOpacity onPress = {()=>this.onTilePress(0,0)} style = {styles.tile} >
             {this.renderIcon(0,0)}
        </TouchableOpacity>
        <TouchableOpacity onPress = {()=>this.onTilePress(0,1)} style = {styles.tile} >
             {this.renderIcon(0,1)} 
        </TouchableOpacity>
        <TouchableOpacity onPress = {()=>this.onTilePress(0,2)} style = {styles.tile} >
              {this.renderIcon(0,2)}
              </TouchableOpacity>
      </View>
      <View style = {{flexDirection:'row'}} >
        <TouchableOpacity onPress = {()=>this.onTilePress(1,0)} style = {styles.tile} >
        {this.renderIcon(1,0)}
        </TouchableOpacity>
        <TouchableOpacity onPress = {()=>this.onTilePress(1,1)} style = {styles.tile} >
        {this.renderIcon(1,1)}
        </TouchableOpacity>
        <TouchableOpacity onPress = {()=>this.onTilePress(1,2)} style = {styles.tile} >
        {this.renderIcon(1,2)}
        </TouchableOpacity>
      </View>
      <View style = {{flexDirection:'row'}} >
        <TouchableOpacity onPress = {()=>this.onTilePress(2,0)} style = {styles.tile} >
        {this.renderIcon(2,0)}
        </TouchableOpacity>
        <TouchableOpacity onPress = {()=>this.onTilePress(2,1)} style = {styles.tile} >
        {this.renderIcon(2,1)}
        </TouchableOpacity>
        <TouchableOpacity onPress = {()=>this.onTilePress(2,2)} style = {styles.tile} >
        {this.renderIcon(2,2)}
        </TouchableOpacity>
      </View>
      <View style = {{paddingTop:80}}></View>
      <View style = {styles.button}><Button title = "NEW GAME " onPress = {this.onNewGamePress } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 1" onPress = {this.onGoPress(1) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 2" onPress = {this.onNewGamePress(2) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 3" onPress = {this.onNewGamePress(3) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 4" onPress = {this.onNewGamePress(4) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 5" onPress = {this.onNewGamePress(5) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 6" onPress = {this.onNewGamePress(6) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 7" onPress = {this.onNewGamePress(7) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 8" onPress = {this.onNewGamePress(8) } /></View>
      <View style = {styles.button}><Button title = "Go to move no: 9" onPress = {this.onNewGamePress(9) } /></View>

    </View>
    </ScrollView>
  );
}
}

   

Отсутствуют скобки, где вы меняете это: this.setState({ gameState: history })

kellys 19.03.2022 14:49
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Массив зависимостей в React
Массив зависимостей в React
Все о массиве Dependency и его связи с useEffect.
0
1
24
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий
  onGoPress=()=>{
    this.setState(gameState:history) //change this line
    this.setState({gameState:history}) //to this
  }

Прочтите "Как ответить" и "Объяснение полностью основанных на коде ответов". Это поможет больше, если вы объясните, почему это решение является предпочтительным, и объясните, как оно работает. Мы хотим обучать, а не просто предоставлять код.

the Tin Man 20.03.2022 23:56

Другие вопросы по теме