我已经被这个问题困扰了很长时间,答案可能很简单,但我根本无法弄清楚,基本上每次我单击按钮绘制卡片时,它都会给我一个全新的牌组,而不是将牌组与与我试图提取的 ID 相同。如果不是显而易见的话,我是新人,谢谢。
let deckOfCardsApi = 'https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1'
const button = document.querySelector('#giveCardButton');
const drawCard = async () => {
try {
const response = await axios.get(deckOfCardsApi);
let deckId = response.data.deck_id;
const drawCard = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`)
console.log(deckId);
} catch (error) {
console.error('Error fetching data:', error);
}
};
button.addEventListener('click', drawCard);
我尝试制作两个单独的异步函数,一个用于召唤新牌组,另一个用于从牌组中拉出,但这不起作用。还一直在查看 api 网站,看看我是否输入了任何错误,但看起来并非如此。
当您点击抽卡按钮时,每次都会调用
deckOfCardsApi
函数,每次都会给您新的牌组,这就是您从全新牌组中获得牌的原因。
简单的解决方案
// API endpoint for creating a new shuffled deck
const deckOfCardsApi = 'https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1';
const button = document.querySelector('#giveCardButton');
let deckId;
const drawCard = async () => {
try {
if (!deckId) {
// If we don't have a deck ID, create a new deck
const response = await axios.get(deckOfCardsApi);
deckId = response.data.deck_id;
console.log('New deck created with ID:', deckId);
}
// Draw a card from the deck
const drawResponse = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`);
} catch (error) {
console.error('Error:', error.message);
}
};
button.addEventListener('click', drawCard);