首页 > 解决方案 > 为什么我不能在 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();
  }, []);

标签: javascriptreactjsreact-hooksreact-state

解决方案


首先,第一个状态是[]

const [deckWithCards, setDeckWithCards] = useState([]);

因此,在第一次运行时,我除了那deckWithCards是一个没有属性的数组cards。这可能会触发您遇到的错误。

否则,如果deckWithCards是一个对象数组,那么要访问卡,比如说,第一个对象,你需要输入deckWithCards[0].cards

相反,如果deckWithCards您如上所述正确设置对象的值,deckWithCards.cards则应正确返回例外的卡片列表。


推荐阅读