這6個(gè)React技巧讓你獲得愉悅工作體驗(yàn)
俗話說,熟能生巧,大多數(shù)時(shí)候筆者都在使用React工作。時(shí)間久了,一些小技巧也不請自來,它們著實(shí)讓人獲得了意外之喜。
并不是每個(gè)人都發(fā)現(xiàn)了這些技巧,筆者的很多同事就還沒有發(fā)現(xiàn)。但它們確實(shí)簡單好用,讓人心情愉悅。一起來看看吧!
以下所有例子均圍繞功能性組件(components)和鉤子(hooks)展開。
React 帶鍵的片段
有時(shí),需要在列表內(nèi)渲染多種組件。如果不需要容器,就可以使用React 片段。示例如下:
- const pokemons = ['Charizard', 'Mr. Mime', 'Jynx']
- pokemons.map(pokemon => (
- <>
- <strong>Name: </strong>
- <span>{pokemon}</span>
- </>
- ))
上述代碼沒有問題,但React會(huì)對鍵進(jìn)行提示:
- Warning: Each child in a listshould have a unique "key" prop.
程序猿一般會(huì)認(rèn)為這沒什么大不了,用div替換片段就好啦。
這么做當(dāng)然沒有問題,但如果改可以使用帶鍵的React片段,即使用
- pokemons.map(pokemon => (
- <React.Fragmentkey={pokemon}>
- <strong>Name: </strong>
- <span>{pokemon}</span>
- </React.Fragment>
- ))
向setState傳遞函數(shù)
useState和useEffect恐怕是比較常使用的鉤子了。程序員需要向useEffect傳遞依賴項(xiàng),否則就會(huì)出錯(cuò)或會(huì)出現(xiàn)意外結(jié)果。然而,如果依賴項(xiàng)僅僅是和相關(guān) setState連用的狀態(tài),或許就無需對其進(jìn)行傳遞了。
先來看個(gè)不太完美的版本:
- const [count, setCount] =useState(0)
- useEffect(() => {
- const id =setInterval(() => {
- setCount(count +1);
- }, 1000);
- return () =>clearInterval(id);
- }, [count]);
更新之后是什么樣呢:
- const [count, setCount] =useState(0)
- useEffect(() => {
- const id =setInterval(() => {
- setCount(c => c +1);
- }, 1000);
- return () =>clearInterval(id);
- }, []);
用useReducer實(shí)現(xiàn)useState
這是筆者在推特上發(fā)現(xiàn)的,盡管沒有實(shí)際作用,但可以了解 useReducer的能力。
如果直接從useReducer進(jìn)行返回操作,那么它將和useState起到幾乎同樣的作用。有人可能會(huì)說使用useState沒有必要。那篇推文是這樣講的:

代碼如下,可自行拷貝嘗試:
- const [name, setName] =useReducer((_, value) => value, 'James');<input value={name} onChange={e =>setName(e.target.value)} />
將字符串值作為HTML元素
有時(shí),程序員希望創(chuàng)建一個(gè)能夠成為靈活HTML元素的組件?;蛟S讀者見過來自CSS-in-JS庫的as prop,比如emotion。
假設(shè)要?jiǎng)?chuàng)建一個(gè)能夠渲染為button或 a 的<Button> 組件,有哪些選擇呢?可以用它提取樣式,創(chuàng)建兩個(gè)不同的組件;也可以只創(chuàng)建一個(gè)組件,一起使用 React.createElement 和 as prop:
- constButton= ({ as ='button', ...props }) => React.createElement(as, props)
- <Button>A Button</Button> // Renders a button element
- <Buttonas="a">A Link</Button> // Renders an anchor element
對于簡單的組件來說,這已經(jīng)很不錯(cuò)了,但有沒有更好的方法呢?看看這個(gè)::
- constButton= ({ Component ='button', ...props }) => <Component {...props} />
- <Button>A Button</Button> // Renders a button element
- <ButtonComponent="a">A Link</Button> // Renders an anchor element
沒錯(cuò),可以在JSX中把字符串作為組件——保證字符串組件的名稱以大寫字母打頭即可。
手動(dòng)對組件進(jìn)行重新渲染
你一定有過需要手動(dòng)對組件進(jìn)行重新渲染的經(jīng)歷吧?比如,需要重新渲染組件的時(shí)候,手頭沒有任何狀態(tài)或可用的物件。
假設(shè)處于某些特殊原因,需要在點(diǎn)擊按鈕時(shí)進(jìn)行此項(xiàng)操作,可以這么做:
- const [, rerender] =useState()rerender({})
代碼中用到了useState,但不需要狀態(tài)本身。需要的只是 setState函數(shù)或rerender 函數(shù),以達(dá)到重新渲染的目的。Bingo!
需要注意的是,每次運(yùn)行時(shí),都需要傳遞一個(gè)新的值,比如一個(gè)空白對象或數(shù)組。
若無直接可用的prop或狀態(tài)依賴項(xiàng),可將對象或函數(shù)從組件中移除
這是很常見的錯(cuò)誤,首來看代碼:
- constPokemon= ({ type, name }) => {
- const cardProps = {
- fire: { primaryColor:'red', secondaryColor:'yellow' },
- ice: { primaryColor:'blue', secondaryColor:'white' }
- }
- return <Card {...cardProps[type]}>Name: {name}</Card>
- }
想法不錯(cuò)——比使用if/else或 switch語法好多了。但還是有問題。該組件每次都會(huì)重新渲染一個(gè)新創(chuàng)建的cardProps對象。即使沒有任何改變,對所有依賴組件的重新渲染還是會(huì)發(fā)生。
使用useMemo 能夠解決這一問題:
- constPokemon= ({ type, name }) => {
- const cardProps =useMemo(() => ({
- fire: { primaryColor:'red', secondaryColor:'yellow' },
- ice: { primaryColor:'blue', secondaryColor:'white' }
- }), [])
- return <Card {...cardProps[type]}>Name: {name}</Card>
- }
但這樣做要付出代價(jià)。仔細(xì)觀察代碼就不難發(fā)現(xiàn),把cardProps對象放到組件里沒有必要。所以把 useMemo 放上去也沒必要,因?yàn)閷ο笤趐rops或狀態(tài)上沒有直接的依賴項(xiàng)。即使來自外部,還是可以使用...cardProps[types]。
- const cardProps = {
- fire: { primaryColor:'red', secondaryColor:'yellow' },
- ice: { primaryColor:'blue', secondaryColor:'white' }
- }
- constPokemon= ({ type, name }) => <Card{...cardProps[type]}>Name: {name}</Card>
看到了吧,無需任何鉤子。如果不需要,就移除它們——函數(shù)也是同理。
學(xué)無止境,值得探索的東西還很多,這些技巧你學(xué)會(huì)了嘛~