我试图使用反应钩子来解决一个简单的问题

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钩子useState在函数中被调用 “app”既不是React函数组件,也不是自定义React 钩子函数react-hooks/rules-of-hooks 39行: 'state'没有定义 no-undef 搜索关键字以了解关于每个错误的更多信息。

组件代码如下:

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; 

当前回答

解决方法很简单,把“app”写正确,并把“app”的第一个字母大写。

其他回答

首先,你需要大写你的组件的FirstLetter,在你的情况下app应该是app, person应该是person。

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

这是CodeSandbox中的链接:无效钩子调用。

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

ReactDOM.render(App(), rootElement);

它应该是:

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

更多信息,你应该阅读规则的钩子-反应

希望这能有所帮助!

我也有同样的问题。事实证明,把“App”中的“A”大写才是问题所在。 另外,如果你要导出:导出默认App;确保你导出了相同的名字“App”。

在JSX中,小写标记名被认为是html原生组件。 为了让react能够将该函数识别为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

就像最佳实践一样,在Person组件中使用props元素之前,尝试解构它。也要使用函数组件而不是常量。(这样更容易混淆,你可以更快地完成任务)

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

将app大写为app肯定会起作用。