反应:更改useState中设置的对象的值

时间:2020-03-09 09:18:43

标签: javascript reactjs

我需要更新嵌套在对象中的数组中的对象,到目前为止,我已经成功使用useState和传播语法:

playerState = {
        resources: {
            coins: 2,
            ...
        },
        availableAdventurers: 2,
        hand: [],
        activeCard: false,
        drawDeck: [],
        discardDeck: [],
        playedCards: [],
        destroyedCards: []
    };

此更新没有问题:

let tPlayerState = {...playerState};
...
tPlayersState.discardDeck.push(card);
...
setPlayerState(tPlayerState);

但是在这种情况下不起作用:

let tLocations = {...locations};
tLocations[locationLevel][locationIndex].state = LOCATION_STATE.occupied;
console.log("Target location state: " + tLocations[locationLevel][locationIndex].state);
console.log("Locations copy state:");
console.log(tLocations);

虽然第一个日志按预期返回“已占用”,但是当我检查整个对象时,我发现状态没有更改:

"Target location state: occupied"

"Locations copy state:
{…}
​I: (2) […]
  ​​0: Object { type: "brown location", exploreText: {…}, state: "explored", …" }

当我引用同一对象时,我希望在两种情况下都可以看到状态被“占用”,但事实并非如此-为什么?

0 个答案:

没有答案