1.不要忘記在組件卸載時移除監聽器
我們經常需要在React的useEffect中監聽鍵盤事件、鼠標事件等,但是我們經常忘記刪除它們。
const windowScroll = () => {
console.log('scroll')
}
useEffect(() => {
window.addEventListener("scroll", windowScroll, false)
}, [])
是的,當我們回到這個組件的時候,scroll事件又會被監聽。
換句話說,我們可能會將數千個 windowScroll 函數綁定到 window, 這將導致內存泄漏和偵聽器的意外行為。
請不要忘記在組件卸載時移除監聽器。
const windowScroll = () => {
console.log('scroll')
}
useEffect(() => {
window.addEventListener("scroll", windowScroll, false)
return () => {
window.removeEventListener('scroll', windowScroll, false)
}
}, [])
2.請謹慎使用0,它是魔鬼
你可能寫過類似下面的代碼,它顯示了什么?還是什么都沒有顯示?
const App = () => {
const [ list, setList ] = useState([])
return (
list.length && (
<div className="list">
{list.map((name) => {
return <div className="item">{name}</div>
})}
</div>
)
)
}
我不認為這段代碼有什么問題!但是確實顯示了0。難道是React的BUG?
const i = 0
const b = 'fatfish'
console.log(i && b)

我錯了,這不是 React 中的錯誤,它完全符合 JavaScript 語法。
為了避免錯誤顯示0,我們需要使用以下三種方法來解決這個問題。
// 1. Controlled by specific logic
list.length >= 1 && <Component list={list} />
// 2. Convert list.length to boolean
!!list.length && <Component list={list} />
// 3. Use ternary expressions and null
list.length ? <Component list={list} /> : null
3. 如何輕松將 true 傳遞給子元素
我們經常需要在調用一個組件的時候給它傳遞一個布爾值,比如顯式傳遞true。
const Child = ({ showNav }) => {
return !!showNav && <Nav />
}
const Parent = () => {
return <Child showNav = { true } />
}
實際上,您只需要傳遞 showNav 屬性即可, 它們都具有完全相同的效果。
const Child = ({ showNav }) => {
return !!showNav && <Nav />
}
const Parent = () => {
return <Child showNav/>
}
4. 請不要再使用 props.children
請問這段代碼的結果是什么?它是空的嗎?
const Container = ({ children }) => {
if (children) {
return (
<div className="children-container">
<p>Children is:</p>
{ children }
</div>
)
} else {
return (
<div className="empty">empty</div>
)
}
}
const App = () => {
const [ list, setList ] = useState([])
return (
<Container>
{
list.map((name) => {
return <div className="item">{ name }</div>
})
}
</Container>
)
}
不幸的是,答案是:“Children is:”。我的天啊!這是為什么?
其實,此時children是一個空數組,所以肯定會顯示“Children is:”。我們如何解決這個問題?React.Children.toArray 會拯救我們。
const Container = ({ children }) => {
if (React.Children.toArray(children).length) {
return (
<div className="children-container">
<p>children is:</p>
{ children }
</div>
)
} else {
return (
<div className="empty">empty</div>
)
}
}
寫在最后
以上就是今天我跟大家分享的4個非常實用的React技巧,希望能夠幫助到你,編程快樂!