Hooks 是使用 JavaScript 函数定义的,但它们表示一种具有调用位置限制的可重用 UI 逻辑的特殊类型。
只在顶层调用钩子
🌐 Only call Hooks at the top level
在 React 中,名称以 use 开头的函数被称为 Hooks。
🌐 Functions whose names start with use are called Hooks in React.
不要在循环、条件语句、嵌套函数或 try/catch/finally 块中调用 Hooks。 相反,应始终在 React 函数组件的顶层使用 Hooks,在任何提前返回之前。你只能在 React 渲染函数组件时调用 Hooks:
function Counter() {
// ✅ Good: top-level in a function component
const [count, setCount] = useState(0);
// ...
}
function useWindowWidth() {
// ✅ Good: top-level in a custom Hook
const [width, setWidth] = useState(window.innerWidth);
// ...
}在其他情况下调用 Hooks(以 use 开头的函数)不被支持,例如:
🌐 It’s not supported to call Hooks (functions starting with use) in any other cases, for example:
- 🔴 不要在条件或循环中调用 Hooks。
- 🔴 不要在条件
return语句之后调用 Hooks。 - 🔴 不要在事件处理函数中调用 Hooks。
- 🔴 不要在类组件中调用 Hooks。
- 🔴 不要在传递给
useMemo、useReducer或useEffect的函数内部调用 Hooks。 - 🔴 不要在
try/catch/finally块中调用 Hooks。
如果你违反这些规则,你可能会看到此错误。
🌐 If you break these rules, you might see this error.
function Bad({ cond }) {
if (cond) {
// 🔴 Bad: inside a condition (to fix, move it outside!)
const theme = useContext(ThemeContext);
}
// ...
}
function Bad() {
for (let i = 0; i < 10; i++) {
// 🔴 Bad: inside a loop (to fix, move it outside!)
const theme = useContext(ThemeContext);
}
// ...
}
function Bad({ cond }) {
if (cond) {
return;
}
// 🔴 Bad: after a conditional return (to fix, move it before the return!)
const theme = useContext(ThemeContext);
// ...
}
function Bad() {
function handleClick() {
// 🔴 Bad: inside an event handler (to fix, move it outside!)
const theme = useContext(ThemeContext);
}
// ...
}
function Bad() {
const style = useMemo(() => {
// 🔴 Bad: inside useMemo (to fix, move it outside!)
const theme = useContext(ThemeContext);
return createStyle(theme);
});
// ...
}
class Bad extends React.Component {
render() {
// 🔴 Bad: inside a class component (to fix, write a function component instead of a class!)
useEffect(() => {})
// ...
}
}
function Bad() {
try {
// 🔴 Bad: inside try/catch/finally block (to fix, move it outside!)
const [x, setX] = useState(0);
} catch {
const [x, setX] = useState(1);
}
}你可以使用 eslint-plugin-react-hooks 插件 来捕捉这些错误。
🌐 You can use the eslint-plugin-react-hooks plugin to catch these mistakes.
仅从 React 函数调用钩子
🌐 Only call Hooks from React functions
不要在普通的 JavaScript 函数中调用 Hooks。相反,你可以:
🌐 Don’t call Hooks from regular JavaScript functions. Instead, you can:
✅ 从 React 函数组件中调用 Hooks。 ✅ 从 自定义 Hooks 中调用 Hooks。
通过遵循此规则,你可以确保组件中的所有状态逻辑从其源代码中清晰可见。
🌐 By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
function FriendList() {
const [onlineStatus, setOnlineStatus] = useOnlineStatus(); // ✅
}
function setOnlineStatus() { // ❌ Not a component or custom Hook!
const [onlineStatus, setOnlineStatus] = useOnlineStatus();
}