用字典设置状态在REACT中不起作用

时间:2018-08-09 20:56:28

标签: arrays reactjs react-state-management

我目前正在学习REACT,但该州仍存在一些问题。 看来我无法使用字典setState。

class Game extends React.Component {
  state = {
    selectedCharacters: [{"name":"Loup Garou","imgName":"base_loup.png","uniqueKey":"loup","playerName":""},{"uniqueKey":"voyante","imgName":"base_voyante.png","name":"Voyante","maxInGame":1,"left":1}],
    turnList: [],
    gameStatus: "characterSelection",
  };
  saveStateToStorage() {
    localStorage.setItem("gameState", JSON.stringify(this.state));
  }
  startGame = () => {
    //Démarre la partie
    var turns = this.createTurnListFromSelectedCharacters();
    console.log(turns);
    this.setState({
        turnList: turns,
        gameStatus: "gameStarted",
      },
      () => {
        //Sauvegarde l'état du jeu dans le local storage
        this.saveStateToStorage();
        console.log(this.state.turnList);
      }
    );
  };
  createTurnListFromSelectedCharacters = () => {
    //Création de la liste des tours  ainsi que du compteur de joueur en vie
    var turns = [];  
    for (var i = 0; i < this.state.selectedCharacters.length; i++)
    {
      var char = this.state.selectedCharacters[i];
      var turn = turns[char.uniqueKey];
      if (turn === undefined) {
        var namesList = [{ name: char.playerName, isAlive: true }];
        var newTurn = {
          charKey: char.uniqueKey,
          alive: 1,
          inGame: 1,
          names: namesList,
          imgName: char.imgName
        };
        turns[char.uniqueKey] = newTurn;
      }
      else {
        turn.names.push({ name: char.playerName, isAlive: true });
        turn.alive = turn.alive + 1;
        turn.inGame = turn.inGame + 1;
        turns[char.uniqueKey] = turn;
      }
    }
    return turns;
  };  
  render() {...}
}

第一个console.log显示由我的函数createTurnListFromSelectedCharacters正确生成的字典,第二个console.log在setState回调中不显示任何内容。 如果我将诸如'turnList:[1,2,3,4,5]之类的东西或setState中的任何数组放进去,那么它将起作用。

3 个答案:

答案 0 :(得分:1)

您使用的是数组[],而不是字典的对象。请改用常规对象。

class Game extends React.Component {
  state = {
    selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
    turnList: {},
    gameStatus: "characterSelection",
  };

  componentDidMount() {
    this.startGame();
  }
  saveStateToStorage() {
    localStorage.setItem("gameState", JSON.stringify(this.state));
  }
  startGame = () => {
    //Démarre la partie
    var turns = this.createTurnListFromSelectedCharacters();
    console.log("foo", turns);
    this.setState({
      turnList: turns,
      gameStatus: "gameStarted",
    },
      () => {
        //Sauvegarde l'état du jeu dans le local storage
        this.saveStateToStorage();
        console.log(this.state.turnList);
      }
    );
  };
  createTurnListFromSelectedCharacters = () => {
    //Création de la liste des tours  ainsi que du compteur de joueur en vie
    var turns = {};
    for (var i = 0; i < this.state.selectedCharacters.length; i++) {
      var char = this.state.selectedCharacters[i];
      console.log( char.uniqueKey );
      var turn = turns[char.uniqueKey];
      if (turn === undefined) {
        var namesList = [{ name: char.playerName, isAlive: true }];
        var newTurn = {
          charKey: char.uniqueKey,
          alive: 1,
          inGame: 1,
          names: namesList,
          imgName: char.imgName
        };
        turns[char.uniqueKey] = newTurn;
      }
      else {
        turn.names.push({ name: char.playerName, isAlive: true });
        turn.alive = turn.alive + 1;
        turn.inGame = turn.inGame + 1;
        turns[char.uniqueKey] = turn;
      }
    }
    return turns;
  };
  render() {
    const { turnList } = this.state;
    return (
        <div>{
        Object.keys(turnList).map( key => (
            <div key={turnList[ key ].charKey}>
            <p>Charkey: {turnList[ key ].charKey}</p>
            <p>Alive: {turnList[ key ].alive}</p>
        </div>
    ))
  }</div>
);
  }
}

ReactDOM.render(<Game />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

答案 1 :(得分:0)

您需要在构造方法中设置状态,例如:

class Game extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
      turnList: [],
      gameStatus: "characterSelection",
    };
  }
  ...
}

答案 2 :(得分:0)

如果我将devserkan的答案与在另一个主题上发现的东西结合在一起。 我明白了:

class Game extends React.Component {
  state = {
    selectedCharacters: [{ "name": "Loup Garou", "imgName": "base_loup.png", "uniqueKey": "loup", "playerName": "" }, { "uniqueKey": "voyante", "imgName": "base_voyante.png", "name": "Voyante", "maxInGame": 1, "left": 1 }],
    turnList: {},
    gameStatus: "characterSelection",
  };
  startGame = () => {
    //Démarre la partie
    var turns = this.createTurnListFromSelectedCharacters();
    console.log("foo", turns);
    this.setState({
      turnList: turns,
      gameStatus: "gameStarted",
    },
      () => {
        //Sauvegarde l'état du jeu dans le local storage
        this.saveStateToStorage();
        console.log(this.state.turnList);
      }
    );
  };
  createTurnListFromSelectedCharacters = () => {
    //Création de la liste des tours  ainsi que du compteur de joueur en vie
    var turns = {};
    for (var i = 0; i < this.state.selectedCharacters.length; i++) {
      var char = this.state.selectedCharacters[i];
      console.log( char.uniqueKey );
      var turn = turns[char.uniqueKey];
      if (turn === undefined) {
        var namesList = [{ name: char.playerName, isAlive: true }];
        var newTurn = {
          charKey: char.uniqueKey,
          alive: 1,
          inGame: 1,
          names: namesList,
          imgName: char.imgName
        };
        turns[char.uniqueKey] = newTurn;
      }
      else {
        turn.names.push({ name: char.playerName, isAlive: true });
        turn.alive = turn.alive + 1;
        turn.inGame = turn.inGame + 1;
        turns[char.uniqueKey] = turn;
      }
    }
    return turns;
  };
  render() {
    return (
      <div>
        {Object.keys(props.aliveCount).map((turn, i) => {
          return (
            <div>
              <img alt={props.aliveCount[turn].imgName} src= {require("../../public/images/" + props.aliveCount[turn].imgName)} />
              {props.aliveCount[turn].alive}/{props.aliveCount[turn].inGame}
            </div>
          );
        })}
      </div>
    );
  }
}

我需要使用{}设置对象,然后使用Object.keys进行映射。