A: Hooks 不能在 class 组件中使用. 只能在函数组件中使用.
useEffect 让你在函数组件中执行一些副作用(side effect) 数据请求, 订阅数据, 对于 DOM 需要有一些操作, 调用 web 平台的一些 api, 属于副作用. 你可能在 class 组件中执行过这些行为.
如果你对 class 的生命周期了解, 你可以认为 useEffect
Hook 是 componentDidMount
, componentDidUpdate
, componentWillUnmount
的集合.
副作用分为两种, 需要 cleanup 的和不需要 cleanup 的.
不需要 cleanup. 有时候, 我们想要做一些额外的操作在更新 DOM 之后, 网络请求, 手动更新 DOM.
function App() {
const [count, setCount] = React.useState(0)
React.useEffect(() => {
document.title = `you clicked ${count} times`
})
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
需要 cleanup. 有一些副作用, 比如订阅, 事件监听, 我们希望在组件 unmount 的时候和组件更新的时候更新订阅的逻辑
function App() {
const [isDropdownVisible, setIsDropdownVisible] = React.useState(false)
React.useEffect(() => {
const handleDocumentScroll = () => setDropdownVisible(false)
// 页面滚动的时候隐藏 dropdown
document.addEventListener('scroll', handleDocumentScroll)
return () => document.removeEventListener('scroll', handleDocumentScroll)
})
return <Dropdown visible={isDropdownVisible} />
}
性能优化, 跳过不必要的 effect React.useEffect 接受第二个参数, 一个数组, 指明该 effect 的依赖.
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // 只执行当 count 变化的时候
旧问题回顾
Q: 什么是 webpack?
A: 本质上, webpack 是一个为了现代 JavaScript 程序的静态打包工具, 当 webpack 处理你的程序的时候, 其内部构建一个 dependency graph, 其映射每一个你项目需求的 modules, 并且生成一个或者多个 bundle.