【发布时间】:2021-02-10 23:59:10
【问题描述】:
我正在创建一个抽认卡应用程序,我目前正在尝试将抽认卡的正面设置为来自 API 的一些文本。
我的状态:
const [deckWithCards, setDeckWithCards] = useState([]);
deckWithCards 是一副抽认卡,它看起来像:
{name: 'Test Name', description: 'Test Description', id: 3, cards: Array(4)};
当我deckWithCards.cards 时,我得到:
[{id: 1, front: 'Front of card', back: 'Back of Card', deckId: 1}]
如果我在一副牌中有 4 张牌,我会得到一个数组,其中包含 4 个对象以及相应的数据。
我需要访问所有这些信息,但是,当我尝试执行 deckWithCards.cards.front 时,我得到“无法读取未定义的属性 'front'。”
我还尝试循环遍历卡片数组,例如:
let arr = [];
let allCards = deckWithCards.cards;
for (let i = 0; i < allCards.length; i++) {
arr.push(allCards.front);
}
这给了我:“无法读取未定义的属性‘长度’。”
如何访问此卡片数组中的项目?
辅助函数:
export async function readDeck(deckId, signal) {
const url = `${API_BASE_URL}/decks/${deckId}?_embed=cards`;
return await fetchJson(url, { signal });
}
export async function listCards(deckId, signal) {
const url = `${API_BASE_URL}/cards?deckId=${deckId}`;
return await fetchJson(url, { signal });
}
我如何设置我的状态:
useEffect(() => {
const abortController = new AbortController();
readDeck(deckId, abortController.signal)
.then(setDeckWithCards)
.catch(setError)
listCards(deckId, abortController.signal)
.then(setCards)
.catch(error)
return () => abortController.abort();
}, []);
【问题讨论】:
-
使用
deckWithCards.cards[0].front -
您得到的错误描述性很强。变量
deckWithCards.cards未定义。它可能只在开始时发生,但你应该研究它。试试console.log吧。 -
看起来
deckWithCards.cards已定义并且是一个数组,但deckWithCards.cards[0].front将是 ;) -
@Dominik 当我控制台日志
deckWithCards.cards[0]时,它说:“无法读取未定义的属性'0'” -
您的问题将是因为它最初是一个空数组,并且您试图在数据填充到状态之前对其进行处理。在尝试对卡片数据进行处理或渲染之前,请检查
deckWithCards.cards是否存在
标签: javascript reactjs react-hooks react-state