我已经阅读了很多有关此问题的答案,但是它并没有帮助我。
功能组件一次需要订阅事件并从API获取数据以获取状态。
但是状态不能正确更改。
const [games, setGames] = useState(null);
const [activeGame, setActiveGame] = useState(null);
const [pending, setPending] = useState(false);
useEffect(() => {
if (games === null) {
setPending(true);
API.Game.get({}).then((res) => {
if (res.success) {
console.log(res.msg.games) // Returning array of games [{...}, {...}]
setGames(res.msg.games);
setActiveGame(res.msg.activeGame);
// Rendered games, but didn't changed state :/
setTimeout(() => console.log(games), 1000) // Returning null (initial state)
}
setPending(false);
});
API.Socket.emit('subscribe', 'game');
API.Socket.on('addGame', (game) => {
setGames((games) => [...games, game]);
});
API.Socket.on('open', (isReconnect) => {
if (isReconnect) API.Socket.emit('subscribe', 'game');
});
}
}, [games, pending, activeGame]);
根据您提供的答案,我尝试了此操作,但仍然无法正常工作。
const [games, setGames] = useState([null]);
const [activeGame, setActiveGame] = useState(null);
const [pending, setPending] = useState(false);
const fetchGames = async () => {
setPending(true);
const res = await API.DurakGame.get({});
if (res.success) {
setGames(res.msg.games);
setActiveGame(res.msg.activeGame);
}
setPending(false);
return true;
};
useEffect(() => {
fetchGames();
API.Socket.emit('subscribe', 'durak');
API.Socket.on('addGame', (game) => {
setGames((games) => [...games, game]);
});
API.Socket.on('open', (isReconnect) => {
if (isReconnect) API.Socket.emit('subscribe', 'durak');
});
}, []);
答案 0 :(得分:0)
该问题可能由引起的:
我希望能回答您的问题。之前谢谢