我的主要父组件中具有以下状态:
this.state = {
playableCards: [],
openedCard: null,
offeredChips: 0,
activePlayer: 0, // first player is 0, second player is 1
players: [
{
name: "player1",
remainingChips: 11,
cards: [],
score: null
},
{
name: "player2",
remainingChips: 11,
cards: [],
score: null
}
]
};
现在,我有一些方法可以更改状态的不同属性。例如:
takeCard = () => {
const {
activePlayer,
players,
playableCards,
offeredChips,
openedCard
} = this.state;
if(openedCard) {
// Add card to active player
let playersClone = [...players];
playersClone[activePlayer].cards = [
...playersClone[activePlayer].cards,
openedCard
];
// Add any offered chips to active player
playersClone[activePlayer].remainingChips += offeredChips;
this.setState({ players: playersClone }, () =>
this.calculateScore(activePlayer)
);
// Remove card from deck
this.setState({
playableCards: playableCards.filter(function(card) {
return card !== openedCard;
})
});
// Change active player
const nextPlayer = activePlayer === 0 ? 1 : 0;
this.setState({ activePlayer: nextPlayer });
// Reset offered chips to 0
this.setState({ offeredChips: 0 });
// Reset opened card
this.setState({ openedCard: null });
} else {
console.log("Open a card first!");
}
};
如您所见,许多属性仅通过单击事件即可更改(此方法附加到单击事件中)。我想知道这是否是正确的做法,还是应该合并所有setState()
?
答案 0 :(得分:2)
可以调用多个setState,因为React在setState之前内部进行批处理,因此只会调用render
一次。就是说,您在写setState时出错,从而使批处理忽略更改或设置不正确的值的几率很高(例如,您可能基于先前的值针对相同的键调用setState两次,并且可能期望得到与结果不同的结果你得到)。因此,建议您在处理所有值后调用一次setState
// Add card to active player
let playersClone = [...players];
playersClone[activePlayer].cards = [
...playersClone[activePlayer].cards,
openedCard
];
// Add any offered chips to active player
playersClone[activePlayer].remainingChips += offeredChips;
const playableCards = playableCards.filter(function(card) {
return card !== openedCard;
})
// Change active player
const nextPlayer = activePlayer === 0 ? 1 : 0;
// Reset offered chips to 0
// Reset opened card
// Remove card from deck
this.setState({
openedCard: null,
offeredChips: 0,
playableCards,
players: playersClone
}, () =>
this.calculateScore(activePlayer)
);
答案 1 :(得分:1)
您可以更改状态的多个属性。
this.setState({ openedCard: null, offeredChips: 0, activePlayer: nextPlayer });
答案 2 :(得分:0)
您可以更改状态的多个属性。this.setState({value1: 0, value2: 0})