【问题标题】:React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook functionReact Hook "useState" 在函数 "app" 中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数
【发布时间】:2019-09-14 17:31:17
【问题描述】:

我正在尝试使用 react hooks 解决一个简单的问题

const [personState,setPersonState] = useState({ DefinedObject });

具有以下依赖项。

"dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.0"
}

但我仍然收到以下错误:

./src/App.js

第 7 行:
在函数中调用 React Hook “useState” “app”既不是 React 函数组件也不是自定义 React 钩子函数 react-hooks/rules-of-hooks

第 39 行:
“状态”未定义
无非定义

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

组件代码如下:

import React, {useState} from 'react'; 
import './App.css'; 
import Person from './Person/Person'; 

const app = props => { 
    const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], }); 
    return (
        <div className="App"> 
            <h2>This is react</h2> 
            <Person name={personState.person[1].name} age="27"></Person>
            <Person name={personState.person[2].name} age="4"></Person> 
        </div> ); 
    };
    export default app;

人物组件

import React from 'react'; 

const person = props => { 
    return( 
        <div>
            <h3>i am {props.name}</h3>
            <p>i am {props.age} years old</p>
            <p>{props.children}</p>
        </div> 
    )
};

export default person; 

【问题讨论】:

  • 你能分享你的组件代码吗?
  • 从'react'导入反应,{useState};导入'./App.css';从'./Person/Person'导入人; const app= props => { const [personState,setPersonSate]= useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name :'fretbox',年龄:'4'} ], }); return (

    这是反应

    ); };导出默认应用;
  • 阅读这种共享代码简直是地狱,尊重他人
  • 我在 Maximilian React 课程中也遇到了同样的问题。
  • 组件名及其导出名应为 App Replace 1. const app --> const App 2. export default app --> export default App;

标签: reactjs react-hooks


【解决方案1】:

函数名必须以大写字母开头

例如:

const App = props => {

}

不是常量应用

【讨论】:

    【解决方案2】:

    尝试将“应用”名称更改为“应用”

    const App = props => {   
      ...
    };  
    export default App;`
    

    【讨论】:

      【解决方案3】:

      作为最佳实践,尝试在将 props 元素用于 Person 组件之前对其进行解构。还要使用功能组件而不是 const。 (它不那么混乱,你可以更快地完成事情)

      function ({person}) {
        const name={person.name}
        return (
          <h2>{name}</h2>
        )
      }
      

      【讨论】:

        【解决方案4】:

        您的代码

        import React, {useState} from 'react'; 
        import './App.css'; 
        import Person from './Person/Person'; 
        
        const app = props => { 
            const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], }); 
            return (
                <div className="App"> 
                    <h2>This is react</h2> 
                    <Person name={personState.person[1].name} age="27"></Person>
                    <Person name={personState.person[2].name} age="4"></Person> 
                </div> ); 
            };
            export default app;
        

        通过将函数名称设为大写来更改它,像这样

        import React, {useState} from 'react'; 
        import './App.css'; 
        import Person from './Person/Person'; 
        
        const App = props => { 
            const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], }); 
            return (
                <div className="App"> 
                    <h2>This is react</h2> 
                    <Person name={personState.person[1].name} age="27"></Person>
                    <Person name={personState.person[2].name} age="4"></Person> 
                </div> ); 
            };
            export default App;
        

        它会工作的谢谢。

        【讨论】:

          【解决方案5】:

          我认为您选择的课程与我相同,因为您在其中使用了完全相同的变量名称,实际上您在这里遗漏了一点,那就是您将应用程序的名称更改为小写

          export default app
          

          还有一个小错误,就是在 index.js 中改了名字,你在 App.js 里改了名字,但是忘记在 index.js 里改了,你还是这样导入的

          import App from './App.js'
          

          所以你还必须在那里更改名称

          【讨论】:

            【解决方案6】:

            可能是您在无条件之前添加了取决于条件的useEffect

            前:

            useEffect(() => {
              _anyFunction();
            }, []);
                
            useEffect(()=> {
              anyCode....
            }, [response]);
            

            【讨论】:

              【解决方案7】:

              如果您仍在寻找这个问题的答案,所有上述解决方案都可以正常工作,但我仍然会在下面提供运行/正确的代码(已编辑)

              import React, { useState } from 'react';
              import './App.css';
              import Person from './Person/Person'
              
                const App = props => {
                  const [personsState, setPersonsState ] = useState({
                    persons:[
                      {name: 'Ram', age: 20},
                      {name: 'Rahul', age: 24},
                      {name: 'Ramesh', age: 25}
                    ],
                    otherState: 'Some Other value' 
                  });
              
                  const switchNameHandler = () => {
                    //console.log('Click is working');
                    //Dont Do THIS: this.state.persons[0].name = 'singh';
                    setPersonsState({
                      persons:[
                      {name: 'Ram',age: 20},
                      {name: 'Raj', age: 24},
                      {name: 'yts', age: 30} 
                    ]
                  });
                  };
              
                  return (
                    <div className="App">
                      <h1>Nice two one three  Hello i am a noob react developer</h1>
                      <button onClick={switchNameHandler}>Switch Name</button>
                      <Person name={personsState.persons[0].name} age={personsState.persons[0].age} />
                      <Person name={personsState.persons[1].name} age={personsState.persons[1].age}> My hobbies are Gaming</Person>
                      <Person name={personsState.persons[2].name} age={personsState.persons[2].age} />
                    </div>
                  ); 
                  // return React.createElement('div',{className:'App'}, React.createElement('h1', null, 'Hi learning the basics of react'));
              }
              
              export default App;
              

              【讨论】:

              • 感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将有助于未来的读者更好地了解正在发生的事情,尤其是那些刚接触该语言并难以理解概念的社区成员。
              【解决方案8】:

              React 组件(函数式和类)必须以大写字母开头。喜欢

              const App=(props)=><div>Hey</div>
              
              class App extends React.Component{
                 render(){
                   return <div>Hey</div>
                 }
              }
              

              React 通过遵循这个语义来识别用户定义的组件。 React 的 JSX 转换为 React.createElement 函数,该函数返回 dom 节点的对象表示。这个对象的 type 属性告诉它是用户定义的组件还是像 div 这样的 dom 元素。因此,遵循这种语义很重要

              由于 useState 挂钩只能在功能组件(或自定义挂钩)内部使用,这就是您收到错误的原因,因为 react 无法将其识别为用户定义的组件。

              useState 也可以在自定义钩子中使用,用于可重用性和逻辑抽象。所以根据钩子的规则,自定义钩子的名字必须以“use”前缀开头,并且必须是驼峰式

              【讨论】:

              • 是的,我为 react-complete-guide 项目工作
              • 这解决了我的问题,谢谢。问题是函数名称以小后者开头
              【解决方案9】:

              在函数名中使用首字母大写。

              function App(){}
              

              【讨论】:

              • "首先,您需要将组件的 FirstLetter 大写,在您的情况下,app 应该是 App,person 应该是 Person。已经有人写过了...
              • 这已经被回答了,这应该被标记为答案。简单的解决方案解释正确。
              【解决方案10】:

              尝试像“app”一样大写

              const App = props => {...}
              
              export default App;
              

              在React中,组件需要大写,自定义钩子需要以use开头。

              【讨论】:

              • 这是一个应用程序中难以发现的错误,我认为应该在错误消息中添加另一条注释以指出这种可能性。
              • 原因是在Rules of Hooks ESLint plugin中,有一个组件或函数名是否有效的检查:Checks if the node is a React component name. React component names must always start with a non-lowercase letter.
              • 在应用程序中大写 A 对我有用...但我不是在想为什么 max 在 udemy 课程中没有收到此错误?
              • 同样的问题“为什么 max 没有收到任何错误?我将“app”更改为“App”,现在它对我有用!
              【解决方案11】:
              React Hook "useState" is called in function "App" which is neither a React function component or a custom React Hook function"
              

              对于以下错误,将组件首字母大写,也将导出。

              const App  = props => {
              ...}
              export default App;
              

              【讨论】:

                【解决方案12】:

                使函数名大写。这对我有用。

                export default function App() { }
                

                【讨论】:

                  【解决方案13】:

                  使用大写字母来定义功能组件名称/React 挂钩自定义组件。 "const 'app' 应该是 const 'App'。

                  App.js

                  import React, { useState } from 'react';
                  import { Component } from 'react';
                  import logo from './logo.svg';
                  import './App.css';
                  import Person from './Person/Person';
                  
                  const App = props => {
                    const [personState, setPersonState] = useState({
                      persons : [
                            {name: 'a', age: '1'},
                            {name: 'b', age: '2'},
                            {name: 'c', age: '3'}
                      ]
                    });
                  
                      return (
                        <div>
                       <Person name = {personState.persons[0].name} age={personState.persons[0].age}> First </Person>
                       <Person name = {personState.persons[1].name} age={personState.persons[1].age}> Second </Person>
                       <Person name = {personState.persons[2].name} age={personState.persons[2].age}> Third </Person>    
                      );
                  };
                  export default App;
                  

                  Person.js

                  import React from 'react';
                  
                  const person = (props) => {
                  return (
                          <div>
                  <p> My name is {props.name} and my age is {props.age}</p>
                  <p> My name is {props.name} and my age is {props.age} and {props.children}</p>
                  <p>{props.children}</p>
                          </div>
                  )
                  };
                  

                  [ReactHooks] [useState] [ReactJs]

                  【讨论】:

                    【解决方案14】:

                    在应用程序功能中,您拼错了单词setpersonSate,缺少字母t,因此应该是setpersonState

                    错误

                    const app = props => { 
                        const [personState, setPersonSate] = useState({....
                    

                    解决方案

                    const app = props => { 
                            const [personState, setPersonState] = useState({....
                    

                    【讨论】:

                      【解决方案15】:
                              import React, { useState } from "react"
                      
                          const inputTextValue = ({ initialValue }) => {
                              const [value, setValue] = useState(initialValue);
                              return {
                                  value,
                                  onChange: (e) => { setValue(e.target.value) }
                              };
                          };
                      
                          export default () => {
                              const textValue = inputTextValue("");
                              return (<>
                                  <input {...textValue} />
                              </>
                              );
                          }
                      
                      /*"Solution I Tired Changed Name of Funtion in Captial "*/
                      
                          import React, { useState } from "react"
                      
                      const InputTextValue = ({ initialValue }) => {
                          const [value, setValue] = useState(initialValue);
                          return {
                              value,
                              onChange: (e) => { setValue(e.target.value) }
                          };
                      };
                      
                      export default () => {
                          const textValue = InputTextValue("");
                          return (<>
                              <input {...textValue} />
                          </>
                          );
                      }
                      

                      【讨论】:

                        【解决方案16】:

                        替换这个

                        export default app;
                        

                        有了这个

                        export default App;
                        

                        【讨论】:

                          【解决方案17】:

                          每当使用 React 功能组件时,始终保持组件名称的第一个字母为大写,以避免这些 React Hooks 错误。

                          在您的情况下,您已将组件命名为 app,应将其更改为 App,如上所述,以避免 React Hook 错误。

                          【讨论】:

                            【解决方案18】:

                            使用 const App 代替 const app

                            【讨论】:

                              【解决方案19】:

                              函数的第一个字符应该是大写

                              【讨论】:

                              • 哇,我总是忘记这一点。谢谢:)
                              【解决方案20】:

                              不要使用箭头函数来创建功能组件。

                              按照以下示例之一进行操作:

                              function MyComponent(props) {
                                const [states, setStates] = React.useState({ value: '' });
                              
                                return (
                                  <input
                                    type="text"
                                    value={states.value}
                                    onChange={(event) => setStates({ value: event.target.value })}
                                  />
                                );
                              }
                              

                              或者

                              //IMPORTANT: Repeat the function name
                              
                              const MyComponent = function MyComponent(props) { 
                                const [states, setStates] = React.useState({ value: '' });
                              
                                return (
                                  <input
                                    type="text"
                                    value={states.value}
                                    onChange={(event) => setStates({ value: event.target.value })}
                                  />
                                );
                              };
                              

                              如果您对"ref" 有问题(可能在循环中),解决方案是使用forwardRef()

                              // IMPORTANT: Repeat the function name
                              // Add the "ref" argument to the function, in case you need to use it.
                              
                              const MyComponent = React.forwardRef( function MyComponent(props, ref) {
                                const [states, setStates] = React.useState({ value: '' });
                              
                                return (
                                  <input
                                    type="text"
                                    value={states.value}
                                    onChange={(event) => setStates({ value: event.target.value })}
                                  />
                                );
                              });
                              

                              【讨论】:

                              • 你能解释一下,为什么“不要使用箭头函数来创建功能组件”。 ? - 谢谢
                              • 为了避免useState()在某些情况下出现问题,比如本例:codesandbox.io/s/usestate-error-f452s
                              【解决方案21】:

                              请尝试将您的应用名称大写

                              const App = props => {...}
                              
                              export default App;
                              

                              【讨论】:

                              • 您是指文档标题吗?
                              • 它的工作,谢谢
                              【解决方案22】:

                              在 JSX 中,小写的标签名被认为是 html 原生组件。 为了将函数识别为 React 组件,需要将名称大写。

                              Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.
                              

                              https://reactjs.org/docs/jsx-in-depth.html#html-tags-vs.-react-components

                              【讨论】:

                                【解决方案23】:

                                将应用程序大写为应用程序肯定会起作用。

                                【讨论】:

                                  【解决方案24】:

                                  React 组件名称应大写,自定义钩子函数应以 use 关键字开头,以标识为反应钩子函数。

                                  因此,将您的 app 组件大写为 App

                                  【讨论】:

                                    【解决方案25】:

                                    第 1 步: 将文件名 src/App.js 改为 src/app.js

                                    第 2 步: 对于“更新 app.js 的导入”,单击“是”。

                                    第 3 步: 重新启动服务器。

                                    【讨论】:

                                      【解决方案26】:

                                      首先,您需要将组件的 FirstLetter 大写,在您的情况下 app 应该是 Appperson 应该是 人。

                                      我试图复制您的代码,希望能找到问题所在。由于您没有分享您如何调用 App 组件,因此我只能看到一种导致问题的方法。

                                      这是 CodeSandbox 中的链接:Invalid hook call

                                      为什么?因为下面的代码是错误的:

                                      ReactDOM.render(App(), rootElement);
                                      

                                      应该是:

                                      ReactDOM.render(<App />, rootElement);
                                      

                                      更多信息,你应该阅读Rule of Hooks - React

                                      希望这会有所帮助!

                                      【讨论】:

                                        【解决方案27】:

                                        正如 Yuki 已经指出的那样,解决方案是将组件名称大写。需要注意的是,不仅“默认” App 组件需要大写,所有组件都需要大写:

                                        const Person = () => {return ...};
                                        
                                        export default Person;
                                        

                                        这是由于 eslint-plugin-react-hooks 包,特别是 RulesOfHooks.js 脚本中的 isComponentName() 函数。

                                        官方解释from Hooks FAQs

                                        我们提供了一个 ESLint 插件,它强制执行 Hooks 规则以避免错误。它假定任何以“use”开头和紧随其后的大写字母的函数都是 Hook。我们认识到这种启发式方法并不完美,并且可能存在一些误报,但是如果没有整个生态系统的约定,就没有办法让 Hooks 很好地工作——而且更长的名称会阻止人们采用 Hooks 或遵循约定。

                                        【讨论】:

                                          【解决方案28】:

                                          解决办法很简单,把“app”改正,把“App”的第一个字符大写。

                                          【讨论】:

                                          • 欢迎来到 StackOverflow(已投票)。请输入一些代码并回答问题。
                                          【解决方案29】:

                                          您收到此错误:“在函数“App”中调用了 React Hook “useState”,该函数既不是 React 函数组件也不是自定义 React Hook 函数”

                                          解决方案:你基本上需要将函数大写。

                                          例如:

                                          const Helper =()=>{}
                                          
                                          function Helper2(){}

                                          【讨论】:

                                            【解决方案30】:

                                            组件应以大写字母开头。还要记得将行中的第一个字母改为导出!

                                            【讨论】:

                                            • 您的问题似乎没有答案。达到 50 代表后,您将能够对问题发表评论。如果您回答 is 是一个答案,请尝试改进它。例如,为什么组件应该以大写字母开头?另外,其他答案已经说过了,你有什么新东西吗?
                                            猜你喜欢
                                            • 2020-03-18
                                            • 2019-10-21
                                            • 2021-11-27
                                            • 1970-01-01
                                            • 2020-12-31
                                            • 2020-11-02
                                            • 2022-01-12
                                            • 1970-01-01
                                            相关资源
                                            最近更新 更多