特点
- 完全可选
- 100% 向后兼容
- 立即可用 Hooks现在已经包含在alpha版本中。而且我们期望在接受社区反馈后把他们加入到React 16.7版本中。
解决了什么
- 跨组件复用stateful logic(包含状态的逻辑)十分困难
- 复杂的组件难以理解
- 不止是用户,机器也对Classes难以理解
useState
const [name, setName] = useState('Mary');
useEffect
如果你熟悉 class 组件中的生命周期方法,你可以把 useEffect Hooks 视作 componentDidMount、componentDidUpdate 和 componentWillUnmount 的结合。 不像 componentDidMount 或者 componentDidUpdate,useEffect 中使用的 effect 并不会阻滞浏览器渲染页面。这让你的 app 看起来更加流畅。尽管大多数 effect 不需要同步调用。但是在一些不常见的情况下你也许需要他们同步调用(比如计算元素尺寸),我们提供了一个单独的 useLayoutEffect 来达成这样的效果。它的 API 和 useEffect 是相同的。
清理effect
useEffect(() => {
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// 明确在这个 effect 之后如何清理它
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
复制代码
React 究竟在什么时候清理 effect? React 在每次组件 unmount 的时候执行清理。 我们没必要在 effect 中返回一个具名函数。我们在这里称它为 清理 就可以表明它的目的,但你也可以返回一个箭头函数或者给它起一个名字。
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
useEffect(() => {
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
}, [props.friend.id]); // Only re-subscribe if props.friend.id changes
复制代码