[英]React useState & useEffect confusion
我對使用 React 功能組件實現某些東西有些困惑。 我知道 useState 是異步的,並且當您在變異 state 后讀取時不反映該值。 但是我不知道如何實現我正在嘗試做的事情。 基本上在我的 React 組件中,當它掛載時,我通過 websocket 連接向服務器詢問一些后端信息,並將其設置在 state 中。 執行此操作后,我立即執行基於開關的方法,但是我無法在該方法中訪問 state,因為我剛剛對 state 進行了變異,並且因為它是異步的,所以更改不會直接反映。 這是我的代碼:
useEffect(() => {
socket.emit("crash:info", (resp) => {
const { status, gameId, gameHistory, mockVariable } = resp;
setGameId(gameId);
setGameHistory(gameHistory);
setStatus(status);
switch (status) {
case 2:
handleGameEnd({ variable: mockVariable });
break;
}
});
}, []);
const handleGameEnd = function (data) {
//other code with this variable...
const { variable } = data;
//here is the issue; gameId is undefined because it is not set by the state yet because setState is async
if (gameHistory.filter((game) => game.gameId === gameId).length > 0) {
return;
}
setGameHistory((gameHistory) => {
const newGameHistory = [...gameHistory];
newGameHistory.unshift({ gameId: gameId });
newGameHistory.pop();
return newGameHistory;
});
};
有人有想法嗎?
反應就像我在對你開玩笑,伙計,你為什么要設置 gameHistory state 兩次你可以做你所有的邏輯然后像這樣在最后調用所有 setStates
useEffect(() => {
socket.emit("crash:info", (resp) => {
const { status, gameId, gameHistory, mockVariable } = resp;
switch (status) {
case 2:
handleGameEnd({ variable: mockVariable, gameId, gameHistory });
break;
}
setStatus(status);
setGameId(gameId);
// you already set gameHistory no need for that
//setGameHistory(gameHistory);
});
}, []);
const handleGameEnd = function (data) {
//other code with this variable...
const { variable, gameId, gameHistory } = data;
//now you have both gameId and gameHistory
if (gameHistory.filter((game) => game.gameId === gameId).length > 0) {
return;
}
setGameHistory((gameHistory) => {
const newGameHistory = [...gameHistory];
newGameHistory.unshift({ gameId: gameId });
newGameHistory.pop();
return newGameHistory;
});
// you can either setState here
setGameId(gameId);
setGameHistory(gameHistory);
// or back to useEffect block
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.