gpt4 book ai didi

javascript - 为什么在React中自定义hook之前必须使用 "use"?

转载 作者:行者123 更新时间:2023-12-02 01:33:58 25 4
gpt4 key购买 nike

为什么我们必须在自定义钩子(Hook)之前使用use。这只是一个命名约定还是 React 正在内部做一些特殊的事情?

CODESANDBOX LINK

我创建了两个自定义 Hook useCustomHookcustomHook 均在下面定义。一种带有前缀 use ,另一种不带有前缀。但是在 customHook eslint 中使用 useState 钩子(Hook)时,会出现错误:

enter image description here

为什么会出现错误。由于自定义钩子(Hook)只是一个普通函数,我们可以在其中使用其他钩子(Hook)。以下是 React 文档中的规则。

Unlike a React component, a custom Hook doesn’t need to have aspecific signature. We can decide what it takes as arguments, andwhat, if anything, it should return. In other words, it’s just like anormal function. Its name should always start with use so that you cantell at a glance that the rules of Hooks apply to it.

useCustomHook:使用 use 前缀

import { useState } from "react";

export default function useCustomHook(initialValue) {
const [value, setValue] = useState(initialValue);

function changeValue() {
setValue((v) => v + 100);
}

return [value, changeValue];
}

customHook:不使用前缀

import { useState } from "react";

export default function customHook(initialValue) {
const [value, setValue] = useState(initialValue);

function changeValue() {
setValue((v) => v + 100);
}

return [value, changeValue];
}

最佳答案

这只是一个命名约定。

不过,这些文档有一点误导性:

In other words, it’s just like a normal function.

就像一个普通函数,但有一个额外的包袱,与普通函数不同,在一个函数内部作为自定义钩子(Hook),你可以调用其中的其他钩子(Hook) - 如果你尝试在 React 上下文之外将其作为普通函数调用,并且在内部使用钩子(Hook),将会失败。

您引用的部分显示了为什么命名约定是这样的:

Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it.

这样一来,一眼就能看出这是一个必须遵循规则的调用钩子(Hook)的组件,而不是不调用钩子(Hook)的组件。

想象一下

const MyComponent = ({ checkThing }) => {
if (checkThing) {
verifyThing();
}

如果 verifyThing 是自定义 Hook ,则上述代码将无效。如果它被重命名为遵循文档和 linter 建议的约定:

const MyComponent = ({ checkThing }) => {
if (checkThing) {
useVerifyThing();
}

很明显存在问题,甚至无需了解 verifyThing/useVerifyMean 的含义或作用。这是在自定义钩子(Hook)前面加上 use 的主要好处 - 它告诉您和钩子(Hook)的其他用户应该始终在功能组件的主体中无条件地调用它,这比搞乱它更有用在某个地方意外地在其他地方调用它,并且必须从运行时错误向后工作来修复它。

关于javascript - 为什么在React中自定义hook之前必须使用 "use"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72851622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com