亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React自定義hook無限渲染

React自定義hook無限渲染

慕仙森 2023-09-28 15:41:59
我制作了一個自定義鉤子,用于獲取新聞 API 并返回用于加載、錯誤和數據的處理程序(受到 Apollo Client 的啟發)。問題是,當使用它時,即使依賴項數組中的項目沒有改變,它也會無限地自行觸發。這就是我的實現方式:鉤子:const useSearch = (query: string, sources: string[]) => {  const [response, setResponse] = useState<State>({    data: null,    loading: true,    error: null,  });  useEffect(() => {    newsapi      .getEverything({        q: query,        pageSize: 1,        sources: sources,      })      .then((data) => {        setResponse({ data, loading: false, error: null });      })      .catch((e) => {        setResponse({ data: null, loading: false, error: e });      });  }, [query, sources]);  return response;};用法:  const { loading, error, data } = useSearch("Donald", ["bbc-news"]);我超出了 API 的每日費率:我究竟做錯了什么?
查看完整描述

1 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

我提供了解決方案,@JacobSmit 在評論部分進行了解釋。現在我只是把它們整理成一個更詳細的答案,希望對后來者有所幫助。


解決方案

const useSearch = (query: string, sources: string[]) => {

  // ...

  useEffect(() => {

    // ...


    // FIX:

    // just apply the spread operator (...) to `sources`

    // to spread its elements into the dependency array of `useEffect`

  }, [query, ...sources]);


  return response;

};

解釋

自useSearch定義掛鉤傳遞[query, sources]到 的 dep 數組useEffect,其中 assources: string[]本身就是一個數組。這使得 dep 數組的形狀為:


["query", ["source_1", "source_2", ..., "source_n"]]

看到 dep 數組的第二個元素是一個嵌套數組。useEffect然而,使用 dep 數組的方法是Object.is對其每個元素應用相等檢查:


// pseudo code

function isDepArrayEqual(prevDepArray: any[], currDepArray: any[]) {

  return prevDepArray.every(

    (prevElement, index) => Object.is(prevElement, currDepArray[index])

  )

}

每次重新渲染時,鉤子調用useSearch("Donald", ["bbc-news"])都會創建一個新的數組實例sources。這將使檢查失敗Object.is(prevSources, currSources),因為數組的相等性是通過它們的引用來比較的,而不是它們包含的值。


使用擴展運算符[query, ...sources],您可以將 dep 數組的形狀轉換為:


["query", "source_1", "source_2", ..., "source_n"]

關鍵區別不在于復制,而在于解壓數組sources。


現在嵌套sources數組已解包,并且 dep 數組的每個元素只是字符串。對字符串的相等性檢查是通過它們的值而不是引用進行比較,因此useEffect將認為 dep 數組不變。錯誤已修復。


查看完整回答
反對 回復 2023-09-28
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號