javascript - 为什么我不能在 React State 上使用点符号?
问题描述
我正在创建一个抽认卡应用程序,我目前正在尝试将抽认卡的正面设置为来自 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();
}, []);
解决方案
首先,第一个状态是[]
const [deckWithCards, setDeckWithCards] = useState([]);
因此,在第一次运行时,我除了那deckWithCards
是一个没有属性的数组cards
。这可能会触发您遇到的错误。
否则,如果deckWithCards
是一个对象数组,那么要访问卡,比如说,第一个对象,你需要输入deckWithCards[0].cards
相反,如果deckWithCards
您如上所述正确设置对象的值,deckWithCards.cards
则应正确返回例外的卡片列表。
推荐阅读
- javascript - 如何将 for 循环的计数器传递给 for 循环中的函数
- javascript - 将 html 模板转换为 Django
- azure - 时间触发 Azure 函数的单元测试示例
- javascript - 如何使用 url 设置属性值?
- php - 如何按一个特定值对数组中的项目进行排序
- origen-sdk - 是否存在基于 Origen 中的变量值的等效 OR 逻辑?
- php - 如何从另一台服务器调用 PHP 函数?
- flutter - 在 Flutter 中显示国旗字符
- python - 尝试使用 python 解析来自 url 的 JSON 数据
- python - 如何为 pika 库上的方法 start_sumption() 添加超时