在温习 hooks 功能时发现原文中有这样一句话
Hooks are JavaScript functions, but they impose two additional rules:
- Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
这个规则确保在每次组件渲染的时候 Hooks 调用顺序一致。 React 会给每个 state hook 关联一个局部变量,这个规则确保在多个 state hook 和 effect hook 调用之间正确的保留 hook 的 state。
- Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks — your own custom Hooks. )
通过遵循这个原则,你可以确保一个组件的所有状态逻辑从其源代码中清晰可见。 (官方解释)
对第二个规则有点费解,相信也有人遇到同样的困惑,所以写这篇博客。
在 React 文档随后的章节中对函数组件进行了定义:
// 第一种
const Example = (props) => {
// You can use Hooks here!
return <div />;
}
// 第二种
function Example