反应状态未更新

React state is not updated

我是新手。我的问题是,在获取之后,allCards 的状态正在改变,但 currentCard 和 showCard 的状态没有改变。

 const [showCard, setShowCard] = useState(false)

  const [allCards, setallCards] = useState<CardProp[]>([]);
  const [currentCard, setcurrentCard] = useState<CardProp>();

  function getRandomCard() {
    return allCards[Math.floor(Math.random() * allCards.length)];
  }
  function updateCard() {
    setcurrentCard(getRandomCard());
  }

  const fetchCards = async () => {
    const cardRequest = await fetch("/api/card", {
      headers: {
        "Content-Type": "application/json",
        Authorization: token!,
      },
    });
    console.log(cardRequest);
    if (cardRequest.status === 200) {
      const cardJSON = await cardRequest.json();
      setallCards(cardJSON.cards);
    }
  };

  useEffect(() => {
    fetchCards();

    if (allCards.length > 0) {
      setcurrentCard(getRandomCard());
      setShowCard(true);
    }
  }, []);

您的 fetchCards() 是一个异步方法。此外,ansynchronous.You 中的 setState 可以像这样使用附加的 useEffect 和依赖项:

useEffect(() => {
      fetchCards();
 }, []);

  useEffect(() => {
     if (allCards.length > 0) {
       setcurrentCard(getRandomCard());
       setShowCard(true);
     }
  }, [allCards]);

你有两个 useEffect,一个是 componentDidMount 的空数组,另一个对 allCards 的变化做出反应

有2个使用效果进行如下更新。

初始渲染,获取卡片

  useEffect(() => {
    fetchCards();
  }, []);

更新当前卡片

  useEffect(() => {
    if (allCards.length > 0) {
      setcurrentCard(getRandomCard());
      setShowCard(true);
    }
  }, [allCards]);

因为fetchCardsasynchronous所以if条件不会在componentDidMount中运行(allCards的首字母是[]

您应该将此逻辑放在另一个 useEffect 中,依赖项是 allCards。获取成功后 allCards 更新时它将 运行。

useEffect(() => {
  if (allCards.length > 0) {
    setcurrentCard(getRandomCard());
    setShowCard(true);
  }
}, [allCards]);