如何在 TypeScript 中使用 useState

huangapple go评论173阅读模式
英文:

How can use useState in typescript

问题

你好,以下是翻译好的部分:

错误:



错误
[eslint]
src\components\text.tsx
第 10 行,第 27 个字符:React Hook “useState” 在函数“atbComponent”中调用,它既不是一个 React 函数组件,也不是一个自定义的 React Hook 函数。React 组件名称必须以大写字母开头。React Hook 名称必须以“use”开头 react-hooks/rules-of-hooks

搜索关键字以了解有关每个错误的更多信息。

在使用之后:

// eslint-disable-next-line react-hooks/rules-of-hooks
let [data, setData] = useState<userData>({
    name: 'abolfazl',
});

但我想知道问题是什么。

英文:

hi im useing typescript in to react and now use useState hook but have an error

my code :

import React , { useState } from &quot;react&quot;;

interface userData {
    name: string;
}

export default function atbComponent() {


    let [data, setData] = useState&lt;userData&gt;({
        name: &#39;abolfazl&#39;,
    });

    

    return (
        &lt;&gt;
            &lt;span&gt;Hi..{data.name}&lt;/span&gt;
        &lt;/&gt;
    )
}

error :



ERROR
[eslint] 
src\components\text.tsx
  Line 10:27:  React Hook &quot;useState&quot; is called in function &quot;atbComponent&quot; 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 &quot;use&quot;  react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.

after use :

// eslint-disable-next-line react-hooks/rules-of-hooks
    let [data, setData] = useState&lt;userData&gt;({
        name: &#39;abolfazl&#39;,
    });

But I want to know what the problem is

答案1

得分: 3

请使用大写字母开头,如果您想将函数用作组件。请将函数名称更改为以下内容。

export default function AtbComponent() {
    let [data, setData] = useState<userData>({
        name: 'abolfazl',
    });
}

请检查错误,该错误明确指出您的函数未遵循 hooks 规则。

英文:

You have to use the Capital letter at starting if you want to use a function as a component. Please change the function name to below.

export default function AtbComponent() {
    let [data, setData] = useState&lt;userData&gt;({
        name: &#39;abolfazl&#39;,
    });
}

Please check the error which clearly indicates that your function is not following the hooks rules.

huangapple
  • 本文由 发表于 2023年6月5日 02:01:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定