簡體   English   中英

為什么我的 UseState 鈎子總是失敗?

[英]Why does my UseState hook keeps on failing?

我想使用UseState掛鈎來更新Table組件中的數據。 要在Table組件中使用的數據由另一個導入paginationForDataAdded的 function 獲取。

由於重新渲染,它看起來像 stackoverflow。 setAllData(searchResults); 將重新渲染組件並再次調用 api 並重新調用。

調用 API 的正確方法。

 const [allData, setAllData] = useState([]);

useEffect(function () {
  const {
    searchResults,
    furnishedData,
    entitledData
  } = paginationForDataAdded({
    searchFunction: search,
    collectionsData: collections
  });
  setAllData(searchResults);
});

假設paginationForDataAdded是一個 function ,它返回一個Promise ,它使用 object 解析,如下所示:

{ 
  searchResults: { resultarray: [...] }, 
  furnishedData: [...], 
  entitledData: [...] 
}

您應該在組件中執行以下操作:

function App(props) {
  const [allData, setAllData] = React.useState([]);
  // ...

  React.useEffect(() => {
    paginationForDataAdded({
      searchFunction: search,
      collectionsData: collections,
    })
    .then(
      ({ searchResults, furnishedData, entitledData }) => {
        const nextAllData = searchResults.resultarray || [];
        setAllData(nextAllData);
      }
    )
    .catch(/* handle errors appropriately */);

    // an empty dependency array so that this hooks runs
    // only once when the component renders for the first time
  }, [])

  return (
    <Table 
      id="pop-table"
      data={allData}
      tableColumns={[...]}
    />
  );
}

但是,如果paginationForDataAdded不是異步調用,那么您應該執行以下操作:

function App(props) {
  const [allData, setAllData] = React.useState([]);
  // ...

  React.useEffect(() => {
    const {
      searchResults,
      furnishedData,
      entitledData,
    } = paginationForDataAdded({
      searchFunction: search,
      collectionsData: collections
    });
    const nextAllData = searchResults.resultarray || [];
    setAllData(nextAllData)

    // an empty dependency array so that this hooks runs
    // only once when the component renders for the first time
  }, [])

  return (
    <Table 
      id="pop-table"
      data={allData}
      tableColumns={[...]}
    />
  );
}

希望這可以幫助。

暫無
暫無

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

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