自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用React Hooks 時(shí)要避免的5個(gè)錯(cuò)誤!

開發(fā) 前端
很有可能你已經(jīng)讀過很多關(guān)于如何使用React Hook 的文章。但有時(shí)候,知道何時(shí)不使用與知道如何使用同樣重要。

[[386276]]

本文已經(jīng)過原作者 Shadeed 授權(quán)翻譯。

很有可能你已經(jīng)讀過很多關(guān)于如何使用React Hook 的文章。但有時(shí)候,知道何時(shí)不使用與知道如何使用同樣重要。

在這篇文章中,主要介紹一下 React hooks 錯(cuò)誤使用方式,以及如何解決它們。

  • 不要更改 Hook 調(diào)用順序
  • 不要使用過時(shí)狀態(tài)
  • 不要?jiǎng)?chuàng)建過時(shí)的閉包
  • 不要將狀態(tài)用于基礎(chǔ)結(jié)構(gòu)數(shù)據(jù)
  • 不要忘記清理副作用

1.不要更改 Hook 調(diào)用順序

在寫這篇文章的前幾天,我編寫了一個(gè)通過id獲取游戲信息的組件,下面是一個(gè)簡(jiǎn)單的版本 FetchGame:

  1. function FetchGame({ id }) { 
  2.   if (!id) { 
  3.     return 'Please select a game to fetch'
  4.   } 
  5.  
  6.   const [game, setGame] = useState({  
  7.     name''
  8.     description: ''  
  9.   }); 
  10.  
  11.   useEffect(() => { 
  12.     const fetchGame = async () => { 
  13.       const response = await fetch(`/api/game/${id}`); 
  14.       const fetchedGame = await response.json(); 
  15.       setGame(fetchedGame); 
  16.     }; 
  17.     fetchGame(); 
  18.   }, [id]); 
  19.  
  20.   return ( 
  21.     <div> <div>Name: {game.name}</div> <div>Description: {game.description}</div> </div> 
  22.   );  

 

組件FetchGame 接收 id(即要獲取的游戲的ID)。useEffect() 在await fetch(/game/${id})提取游戲信息并將其保存到狀態(tài)變量game中。

打開演示(https://codesandbox.io/s/hooks-order-warning-rdxpg?file=/pages/index.js) 。組件正確地執(zhí)行獲取操作,并使用獲取的數(shù)據(jù)更新狀態(tài)。但是看看tab Eslint警告: 有 Hook 執(zhí)行順序不正確的問題。

 

問題發(fā)生在這一判斷:

  1. function FetchGame({ id }) { 
  2.  if (!id) { return 'Please select a game to fetch'; }   
  3.    // ... 

當(dāng)id為空時(shí),組件渲染'Please select a game to fetch'并退出,不調(diào)用任何 Hook。

但是,如果 id不為空(例如等于'1'),則會(huì)調(diào)用useState()和 useEffect()。

有條件地執(zhí)行 Hook 可能會(huì)導(dǎo)致難以調(diào)試的意外錯(cuò)誤。React Hook的內(nèi)部工作方式要求組件在渲染之間總是以相同的順序調(diào)用 Hook。

這正是鉤子的第一條規(guī)則:不要在循環(huán)、條件或嵌套函數(shù)內(nèi)調(diào)用 Hook。

解決方法就是將條件判斷放到 Hook 后面:

  1. function FetchGame({ id }) { 
  2.   const [game, setGame] = useState({  
  3.     name''
  4.     description: ''  
  5.   }); 
  6.  
  7.   useEffect(() => { 
  8.     const fetchGame = async () => { 
  9.       const response = await fetch(`/api/game/${id}`); 
  10.       const fetchedGame = await response.json(); 
  11.       setGame(fetchedGame); 
  12.     }; 
  13.  if (id) {      fetchGame();     }  }, [id]); 
  14.  
  15.  if (!id) { return 'Please select a game to fetch'; } 
  16.   return ( 
  17.     <div> 
  18.  <div>Name: {game.name}</div> 
  19.  <div>Description: {game.description}</div> 
  20.  </div> 
  21.   ); 

 

現(xiàn)在,無論id是否為空,useState()和useEffect() 總是以相同的順序被調(diào)用,這就是 Hook 應(yīng)該始終被調(diào)用的方式。

2.不要使用過時(shí)狀態(tài)

下面的組件MyIncreaser在單擊按鈕時(shí)增加狀態(tài)變量count:

  1. function MyIncreaser() { 
  2.   const [count, setCount] = useState(0); 
  3.  
  4.   const increase = useCallback(() => { 
  5.     setCount(count + 1); 
  6.   }, [count]); 
  7.  
  8.   const handleClick = () { 
  9.  increase(); increase(); increase();  }; 
  10.  
  11.   return ( 
  12.     <> 
  13.  <button onClick={handleClick}>Increase</button> 
  14.  <div>Counter: {count}</div> 
  15.  </> 
  16.   ); 

 

這里有趣一點(diǎn)的是,handleClick調(diào)用了3次狀態(tài)更新。

現(xiàn)在,在打開演示之前,問一個(gè)問題:如果單擊一次按鈕,計(jì)數(shù)器是否增加3?

打開演示(https://codesandbox.io/s/stale-variable-jo32q?file=/src/index.js),點(diǎn)擊按鈕一次,看看結(jié)果。

不好意思,即使在handleClick()中3次調(diào)用了increase(),計(jì)數(shù)也只增加了1。

問題在于setCount(count + 1)狀態(tài)更新器。當(dāng)按鈕被點(diǎn)擊時(shí),React調(diào)用setCount(count + 1)3次

  1. const handleClick = () { 
  2.    increase(); 
  3.    increase(); 
  4.    increase(); 
  5.  }; 
  6.  
  7. / 等價(jià): 
  8.  
  9.  const handleClick = () { 
  10.    setCount(count + 1); 
  11.    // count variable is now stale 
  12.    setCount(count + 1); 
  13.    setCount(count + 1); 
  14.  }; 

setCount(count + 1)的第一次調(diào)用正確地將計(jì)數(shù)器更新為count + 1 = 0 + 1 = 1。但是,接下來的兩次setCount(count + 1)調(diào)用也將計(jì)數(shù)設(shè)置為1,因?yàn)樗鼈兪褂昧诉^時(shí)的stale狀態(tài)。

通過使用函數(shù)方式更新狀態(tài)來解決過時(shí)的狀態(tài)。我們用setCount(count => count + 1)代替setCount(count + 1):

  1. function MyIncreaser() { 
  2.   const [count, setCount] = useState(0); 
  3.  
  4.   const increase = useCallback(() => { 
  5.  setCount(count => count + 1);  }, []); 
  6.  
  7.   const handleClick = () { 
  8.     increase(); 
  9.     increase(); 
  10.     increase(); 
  11.   }; 
  12.  
  13.   return ( 
  14.     <> 
  15.  <button onClick={handleClick}>Increase</button> 
  16.  <div>Counter: {count}</div> 
  17.  </> 
  18.   ); 

 

這里有一個(gè)好規(guī)則可以避免遇到過時(shí)的變量:

如果你使用當(dāng)前狀態(tài)來計(jì)算下一個(gè)狀態(tài),總是使用函數(shù)方式來更新狀態(tài):setValue(prevValue => prevValue + someResult)。

3.不要?jiǎng)?chuàng)建過時(shí)的閉包

React Hook 很大程序上依賴于閉包的概念。依賴閉包是它們?nèi)绱烁挥斜憩F(xiàn)力的原因。

JavaScript 中的閉包是從其詞法作用域捕獲變量的函數(shù)。不管閉包在哪里執(zhí)行,它總是可以從定義它的地方訪問變量。

當(dāng)使用 Hook 接受回調(diào)作為參數(shù)時(shí)(如useEffect(callback, deps), useCallback(callback, deps)),你可能會(huì)創(chuàng)建一個(gè)過時(shí)的閉包,一個(gè)捕獲了過時(shí)的狀態(tài)或變量的閉包。

我們來看看一個(gè)使用useEffect(callback, deps) 而忘記正確設(shè)置依賴關(guān)系時(shí)創(chuàng)建的過時(shí)閉包的例子。

在組件中,useEffect()每2秒打印一次count的值

  1.  const [count, setCount] = useState(0); 
  2.  
  3.   useEffect(function() { 
  4.     setInterval(function log() { 
  5.       console.log(`Count is: ${count}`); 
  6.     }, 2000); 
  7.   }, []); 
  8.  
  9.   const handleClick = () => setCount(count => count + 1); 
  10.  
  11.   return ( 
  12.     <> <button onClick={handleClick}>Increase</button> <div>Counter: {count}</div> </> 
  13.   ); 

 

打開演示(https://codesandbox.io/s/stale-variable-jo32q?file=/src/index.js),點(diǎn)擊按鈕。在控制臺(tái)查看,每2秒打印的都 是 Count is: 0,,不管count狀態(tài)變量的實(shí)際值是多少。

為啥這樣子?

第一次渲染時(shí), log 函數(shù)捕獲到的 count 的值為 0。

之后,當(dāng)按鈕被單擊并且count增加時(shí),setInterval取到的 count 值仍然是從初始渲染中捕獲count為0的值。log 函數(shù)是一個(gè)過時(shí)的閉包,因?yàn)樗东@了一個(gè)過時(shí)的狀態(tài)變量count。

解決方案是讓useEffect()知道閉包log依賴于count,并正確重置計(jì)時(shí)器

  1. function WatchCount() { 
  2.   const [count, setCount] = useState(0); 
  3.  
  4.   useEffect(function() { 
  5.     const id = setInterval(function log() { 
  6.       console.log(`Count is: ${count}`); 
  7.     }, 2000); 
  8.  return () => clearInterval(id); }, [count]); 
  9.   const handleClick = () => setCount(count => count + 1); 
  10.  
  11.   return ( 
  12.     <> 
  13.  <button onClick={handleClick}>Increase</button> 
  14.  <div>Counter: {count}</div> 
  15.  </> 
  16.   ); 

 

正確設(shè)置依賴關(guān)系后,一旦count發(fā)生變化,useEffect()就會(huì)更新setInterval()的閉包。

為了防止閉包捕獲舊值:確保提供給 Hook 的回調(diào)函數(shù)中使用依賴項(xiàng)。

4.不要將狀態(tài)用于基礎(chǔ)結(jié)構(gòu)數(shù)據(jù)

有一次,我需要在狀態(tài)更新上調(diào)用副作用,在第一個(gè)渲染不用調(diào)用副作用。useEffect(callback, deps)總是在掛載組件后調(diào)用回調(diào)函數(shù):所以我想避免這種情況。

我找到了以下的解決方案

  1. function MyComponent() { 
  2.   const [isFirst, setIsFirst] = useState(true); 
  3.   const [count, setCount] = useState(0); 
  4.  
  5.   useEffect(() => { 
  6.     if (isFirst) { 
  7.       setIsFirst(false); 
  8.       return
  9.     } 
  10.     console.log('The counter increased!'); 
  11.   }, [count]); 
  12.  
  13.   return ( 
  14.     <button onClick={() => setCount(count => count + 1)}> Increase </button> 
  15.   ); 

狀態(tài)變量isFirst用來判斷是否是第一次渲染。一旦更新setIsFirst(false),就會(huì)出現(xiàn)另一個(gè)無緣無故的重新渲染。

保持count狀態(tài)是有意義的,因?yàn)榻缑嫘枰秩?count 的值。但是,isFirst不能直接用于計(jì)算輸出。

是否為第一個(gè)渲染的信息不應(yīng)存儲(chǔ)在該狀態(tài)中?;A(chǔ)結(jié)構(gòu)數(shù)據(jù),例如有關(guān)渲染周期(即首次渲染,渲染數(shù)量),計(jì)時(shí)器ID(setTimeout(),setInterval()),對(duì)DOM元素的直接引用等詳細(xì)信息,應(yīng)使用引用useRef()進(jìn)行存儲(chǔ)和更新。

我們將有關(guān)首次渲染的信息存儲(chǔ)到 Ref 中:

  1. const isFirstRef = useRef(true);  const [count, setCount] = useState(0); 
  2.  
  3.  useEffect(() => { 
  4.    if (isFirstRef.current) { 
  5.      isFirstRef.current = false
  6.      return
  7.    } 
  8.    console.log('The counter increased!'); 
  9.  }, [count]); 
  10.  
  11.  return ( 
  12.    <button onClick={() => setCounter(count => count + 1)}> 
  13. Increase 
  14. </button> 
  15.  ); 

isFirstRef是一個(gè)引用,用于保存是否為組件的第一個(gè)渲染的信息。isFirstRef.current屬性用于訪問和更新引用的值。

重要說明:更新參考isFirstRef.current = false不會(huì)觸發(fā)重新渲染。

5.不要忘記清理副作用

很多副作用,比如獲取請(qǐng)求或使用setTimeout()這樣的計(jì)時(shí)器,都是異步的。

如果組件卸載或不再需要該副作用的結(jié)果,請(qǐng)不要忘記清理該副作用。

下面的組件有一個(gè)按鈕。當(dāng)按鈕被點(diǎn)擊時(shí),計(jì)數(shù)器每秒鐘延遲增加1:

  1. function DelayedIncreaser() { 
  2.   const [count, setCount] = useState(0); 
  3.   const [increase, setShouldIncrease] = useState(false); 
  4.  
  5.   useEffect(() => { 
  6.     if (increase) { 
  7.       setInterval(() => { 
  8.         setCount(count => count + 1) 
  9.       }, 1000); 
  10.     } 
  11.   }, [increase]); 
  12.  
  13.   return ( 
  14.     <> <button onClick={() => setShouldIncrease(true)}> Start increasing </button> <div>Count: {count}</div> </> 
  15.   ); 

 

打開演示(https://codesandbox.io/s/unmounted-state-update-n1d3u?file=/src/index.js),點(diǎn)擊開始按鈕。正如預(yù)期的那樣,狀態(tài)變量count每秒鐘都會(huì)增加。

在進(jìn)行遞增操作時(shí),單擊umount 按鈕,卸載組件。React會(huì)在控制臺(tái)中警告更新卸載組件的狀態(tài)。

 

修復(fù)DelayedIncreaser很簡(jiǎn)單:只需從useEffect()的回調(diào)中返回清除函數(shù):

  1. // ... 
  2.  
  3.  useEffect(() => { 
  4.    if (increase) { 
  5.      const id = setInterval(() => { 
  6.        setCount(count => count + 1) 
  7.      }, 1000); 
  8. return () => clearInterval(id);    } 
  9.  }, [increase]); 
  10.  
  11.  // ... 

也就是說,每次編寫副作用代碼時(shí),都要問自己它是否應(yīng)該清理。計(jì)時(shí)器,頻繁請(qǐng)求(如上傳文件),sockets 幾乎總是需要清理。

6. 總結(jié)

從React鉤子開始的最好方法是學(xué)習(xí)如何使用它們。

但你也會(huì)遇到這樣的情況:你無法理解為什么他們的行為與你預(yù)期的不同。知道如何使用React Hook還不夠:你還應(yīng)該知道何時(shí)不使用它們。

首先不要做的是有條件地渲染 Hook 或改變 Hook 調(diào)用的順序。無論P(yáng)rops 或狀態(tài)值是什么,React都期望組件總是以相同的順序調(diào)用Hook。

要避免的第二件事是使用過時(shí)的狀態(tài)值。要避免過時(shí) 狀態(tài),請(qǐng)使用函數(shù)方式更新狀態(tài)。

不要忘記指出接受回調(diào)函數(shù)作為參數(shù)的 Hook 的依賴關(guān)系:例如useEffect(callback, deps),useCallback(callback, deps),這可以解決過時(shí)閉包問題。

不要將基礎(chǔ)結(jié)構(gòu)數(shù)據(jù)(例如有關(guān)組件渲染周期,setTimeout()或setInterval())存儲(chǔ)到狀態(tài)中。經(jīng)驗(yàn)法則是將此類數(shù)據(jù)保存在 Ref 中。

最后,別忘了清除你的副作用。

~完,我是小智,我要去刷碗了。

作者:Shadeed 譯者:前端小智 來源:dmitripavlutin原文:https://dmitripavlutin.com/react-hooks-mistakes-to-avoid/

 本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。

 

責(zé)任編輯:武曉燕 來源: 大遷世界
相關(guān)推薦

2017-08-17 09:07:45

Python編程代碼

2017-08-29 11:05:00

Python編程錯(cuò)誤

2021-04-29 15:29:52

機(jī)器學(xué)習(xí)人工智能AI

2021-04-22 08:00:00

人工智能機(jī)器學(xué)習(xí)數(shù)據(jù)

2023-01-09 15:16:17

2017-08-02 16:47:43

數(shù)據(jù)數(shù)據(jù)收集數(shù)據(jù)分析

2021-02-24 07:40:38

React Hooks閉包

2023-05-11 09:06:50

錯(cuò)誤IT培訓(xùn)

2018-03-17 09:04:35

2021-12-02 18:07:53

云網(wǎng)絡(luò)部署云端云計(jì)算

2023-06-02 14:24:23

ChatGPT人工智能

2022-10-10 09:00:35

ReactJSX組件

2021-12-03 15:00:18

人工智能自然語(yǔ)言機(jī)器學(xué)習(xí)

2018-07-11 05:24:05

機(jī)器學(xué)習(xí)人工智能數(shù)據(jù)

2024-01-26 06:33:06

數(shù)據(jù)策略決策

2018-04-25 06:21:57

多云云計(jì)算IT

2023-06-07 07:43:06

APIVue 2Vue 3

2022-03-08 09:31:48

云配置云安全

2013-08-27 14:44:05

App icon設(shè)計(jì)ASO應(yīng)用商店優(yōu)化app營(yíng)銷推廣

2013-04-23 10:57:27

iOS開發(fā)App icon設(shè)計(jì)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)