React+TypeScript中useState报错:组件命名规范问题解析
React + TypeScript中useState Hook报错的根本原因解析
问题场景
在React结合TypeScript开发时,调用useState Hook触发了ESLint错误,虽然通过禁用规则暂时规避了问题,但需要明确报错的根本原因。
报错代码
import React, { useState } from "react"; interface userData { name: string; } export default function atbComponent() { let [data, setData] = useState<userData>({ name: 'abolfazl', }); return ( <> <span>Hi..{data.name}</span> </> ) }
ESLint报错信息
ERROR [eslint] src\components\text.tsx Line 10:27: React Hook "useState" is called in function "atbComponent" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks Search for the keywords to learn more about each error.
临时处理方式
// eslint-disable-next-line react-hooks/rules-of-hooks let [data, setData] = useState<userData>({ name: 'abolfazl', });
根本原因
React的核心规则明确:
- React函数组件的名称必须以大写字母开头,React靠这个标识来区分组件和普通函数。
- ESLint的
react-hooks/rules-of-hooks规则会严格校验这一点:只有在React函数组件(首字母大写)或自定义Hook(以use开头的函数)中,才允许调用useState这类内置Hook。
你的组件名atbComponent以小写字母开头,ESLint判定它不是合法的React组件,因此触发了Hook调用的违规提示。
正确解决方案
不需要禁用ESLint规则,只需将组件名修改为大写开头即可:
import React, { useState } from "react"; interface userData { name: string; } // 组件名改为大写开头 export default function AtbComponent() { let [data, setData] = useState<userData>({ name: 'abolfazl', }); return ( <> <span>Hi..{data.name}</span> </> ) }
内容的提问来源于stack exchange,提问作者Abolfazl Tabe Bordbar
相关产品推荐
相关产品推荐

