簡體   English   中英

如何在重新渲染時更新API調用?

[英]How can I update the API call on a re-render?

我正在教自己React Hooks,我想在用戶輸入搜索框時更新API調用。 實時搜索的排序。 我已經收集到該事件僅在頁面加載時觸發,但我該如何解決?

示例: https//codesandbox.io/s/6x1xp57zmk

import React, {useState, useEffect} from 'react';

function App() {

  const [cardNames, setCardName] = useState([])

  const rezCards = async () => {
    //const rez = await fetch('https://api.scryfall.com/cards?page=3')
    const rez = await fetch ('https://api.scryfall.com/catalog/card-names')
    const json = await rez.json()
    setCardName(json.data)
  }

  useEffect(() => {
    rezCards()
  },[])

  return <ul>{cardNames
    .slice(0,50)
    .map(
      (cardName) => {
        return <li key={cardName}>{cardName}</li>
      }
    )}</ul>
}

export default App

問題可能出在這里:

useEffect(() => {
    rezCards()
},[])

您已經離開第二個參數為空數組,這導致useEffect只有當組件安裝運行一次,只是同componentDidMount

如果您希望在更改狀態時觸發useEffect ,則可以添加狀態作為掛鈎的依賴項,例如

const { callThisEffectWhenThisValueIsChanged, changeValue } = useState('');

useEffect(() => {
    // Do anything with here, for eg call APIs
},[callThisEffectWhenThisValueIsChanged])

changeValue(newValue);

因此,在CodeSandbox代碼中,您需要做的就是在依賴searchInput中添加searchInput ,每當搜索輸入發生更改時,它都會再次調用鈎子。

useEffect(() => {
    rezCards();
}, [searchInput]);

永遠記住,只要你的效果使用任何狀態,你需要添加狀態作為效果鈎子的依賴

您可以在React Hook文檔中找到更多信息

你應該看看有什么東西。 為了防止在搜索框上鍵入多個api,請使用一種名為debounce的技術,您可以使用react hook實現此目的:

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(
    () => {
      const handler = setTimeout(() => {
        setDebouncedValue(value);
      }, delay);

      return () => {
        clearTimeout(handler);
      };
    },
    [value, delay],
  );

  return debouncedValue;
}

function App() {

  const debouncedInput = useDebounce(searchInputValue, 300);
  useEffect(() => {
    rezCards()
  },[debouncedInput])
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM