{props.timePerRound - time}s before the next round...
)
}
function Timers(){
return (
)
}
效果:
示例9
可以明显地看出:
抽离前后代码的行为没有改变,只是变得可以复用了而已。
自定义 Hook 的名称以 use 开头。
两个组件Timer 和 Timer2 虽然都使用了useTimer Hook,但不共享state,自定义 Hook 中的 state 和 effect 都是完全隔离的。
只要理解了 Hook API,自定义 Hook 还是很简单的。
Custom Hooks are a convention that naturally follows from the design of Hooks, rather than a React feature.
但不得不说,自定义 Hook 提供了共享代码逻辑的灵活性,这在以前的 React 组件中是不可能的。我们可以编写涵盖各种用例的自定义 Hook,比如表单处理,动画,事件订阅,计时器等等。
4. 参考阅读
Hooks at a Glance:https://reactjs.org/docs/hooks-overview.html
Hooks API Reference:https://reactjs.org/docs/hooks-reference.html
Hooks FAQ:https://reactjs.org/docs/hooks-faq.html
Dan Abramov 写的一些demo:https://codesandbox.io/u/gaearon/sandboxes
Dan Abramov 在 React Conf 2018 上介绍 Hook 的演讲视频:https://youtu.be/dpw9EHDh2bM