javascript - React 钩子(Hook)真的必须以 "use"开头吗?

标签 javascript reactjs react-hooks

让我们创建一个非常简单的钩子(Hook) useDouble返回数字的双倍:

export default function useDouble(nb) {
  return nb * 2;
}
文档 (https://reactjs.org/docs/hooks-custom.html#extracting-a-custom-hook) 内容如下:

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks


但如果我改变 useDoubledouble ,它仍然有效。我什至尝试从 double 调用其他钩子(Hook)钩子(Hook),它仍然有效。
演示:https://codesandbox.io/s/laughing-gareth-usb8g?file=/src/components/WithUseDouble.js
所以我的问题是:是命名钩子(Hook)useXxxxx只是一个约定,还是真的会以某种方式破坏某些东西?如果可以,你能举个例子吗?
谢谢

最佳答案

一个完美的definition of a custom hook将是(注意删除“使用”前缀和“可能使用钩子(Hook)”):

A custom Hook is a JavaScript function that calls other Hooks.


所以我们可以区分 之间辅助函数 定制 Hook .
但是 ,我们无法判断某些函数是否真的在使用钩子(Hook)(我们在运行时知道)。这就是我们使用 static code analyzing tools 的原因(如 eslint )我们分析文本(词汇)而不是意义(语义)。

... This convention is very important. Without it, we wouldn’t be able to automatically check for violations of Rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it. (source)


因此:
// #1 a function
// CAN'T BREAK ANYTHING
function double(nb) {
  return nb * 2;
}

// #2 Still a function, does not use hooks
// CAN'T BREAK ANYTHING
function useDouble(nb) {
  return nb * 2;
}

// #3 a custom hook because hooks are used, 
// CAN BREAK, RULES OF HOOKS
function useDouble(nb) {
  const [state, setState] = useState(nb);
  const doubleState = (n) => setState(n*2);
  return [state,doubleState];
}

Is naming hooks useXxxxx just a convention.


是的,帮助静态分析器警告错误。

Can it really break something somehow?


示例 #2 不能破坏您的应用程序,因为它只是一个不违反 Hooks 规则的“辅助函数”,尽管会有警告。

Could you show an example?

function useDouble(nb) { return nb * 2; }

// <WithUseDouble/>
function WithUseDouble() {
  // A warning violating Rules of Hooks 
  // but useDouble is actually a "helper function" with "wrong" naming
  // WON'T break anything
  if (true) {
    return <h1>8 times 2 equals {useDouble(8)} (with useDouble hook)</h1>
  }
  
  return null;
}

关于javascript - React 钩子(Hook)真的必须以 "use"开头吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66151248/

相关文章:

asp.net - jQuery 验证 - 在点击时使用验证,而不是在提交时

reactjs - React - 使用 useEffect 或直接在 onChange 方法中更改值是否对性能最好?

javascript - React Jest 测试失败 - type.toUpperCase 不是函数

reactjs - React hooks - 如何按需调用useEffect?

c# - 在页面加载事件后从页面调用javascript

javascript - 如何实现依赖于查询字符串的弹出窗口?

javascript - 从其他组件初始化另一个 react 组件

reactjs - 返回 useEffect 中的函数

javascript - 使用 react 钩子(Hook)和 typescript 为操作对象创建接口(interface)的正确方法是什么

javascript - 有没有办法用knockout完全分离模板和 View 模型?