简体   繁体   中英

How do I update a react state object correctly with a variable key?

I am building a simple react board game that consists of rows and columns of tiles that player 1 and 2 can be on.

I store the current location of the players in a state object playerLocation. I store the current player (whose turn it is now) in currentPlayer state.

After a click on a tile, I try to move the current player there and update playerLocation state with the movePlayer function. However instead of updating the playerLocation state object it creates an undefined key on the object. So my suspicion is that I am trying to use the variable [currentPlayer.row] incorrectly.

Can someone help me why? How can I update the state object correctly?

    const [playerLocation, setPlayerLocation] = useState({
        1: {
            row: 2,
            column: 2,
        },
        2: {
            row: 2,
            column: 2,
        },
    });

    const [currentPlayer, setCurrentPlayer] = useState(1);

// location param contains the row and column of the clicked tile

    const movePlayer = (location) => {
       setPlayerLocation({
                ...playerLocation,
                [currentPlayer.row]: location.row,
                [currentPlayer.column]: location.column,
            });
    }

Just add the key of the player as an argument.

const movePlayer = (location, key) => {
  setPlayerLocation((previousPayerLocations) => ({
    ...previousPayerLocations,
    [key]: {
      row: location.row,
      column: location.column,
    },
  }));
};

Your playerLocation state is keeping track of both player positions. When you update that state, you are not specifying which nested object (player number/position) you want to update. I think the way you want to update the state in your movePlayerLocation function is:

const movePlayer = (location) => {
  setPlayerLocation({
     ...playerLocation,
     [currentPlayer]: {
         row: location.row,
         column: location.column,
     }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM