错误:元素类型无效,应为字符串

我正在使用 ReactJS。


我无法弄清楚问题出在哪里。


错误:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。检查App.


const App=()=>{

      const Person=[

         {name:"Liya",age:4},

         {name:"kuru", age:7},

         {name:"belaynesh",age:56}

          ]

    const [currentstate,setStateFn]=useState({Person:Person})

    const incrementAge=()=>{

      let copyOfPerson=[...currentstate.Person];//copy of the person array

        let newstate=copyOfPerson.Person.map((per)=>{

          return {name:per.name,age:per.age+1}

        })

        console.log(newstate)

        setStateFn(newstate)

    }

    return(

      <div>

        {

         currentstate.Person.map((per,index)=>{

           return <Person key={index} name={per.name} age={per.age}></Person>

         })

        }

         <button onClick={()=>{incrementAge()}}>IncrementAge</button>

      </div>


    )

    }

    export default App;

错误是:


 import App from './App';

   5 | import * as serviceWorker from './serviceWorker';

   6 | 

>  7 | ReactDOM.render(

   8 |   <React.StrictMode>

   9 |     <App />

  10 |   </React.StrictMode>,


交互式爱情
浏览 121回答 2
2回答

慕容森

在您的退货声明中,您有return(&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;currentstate.Person.map((per,index)=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return <Person key={index} name={per.name} age={per.age}></Person>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<button onClick={()=>{incrementAge()}}>IncrementAge</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )对于以下行,return <Person key={index} name={per.name} age={per.age}></Person>Person 之前被定义为一个数组,但在这里你试图将它渲染为一个反应组件,因此反应编译器抱怨。

千万里不及你

您将 定义Person为常量数据数组。但是您在功能组件的返回中使用它作为JSX 组件,这导致了您提到的错误。您可以制作Person如下所示的组件const Personal = ({name, age}) => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {name}, {age}&nbsp; &nbsp; </div>&nbsp; )}return <Personal key={index} name={per.name} age={per.age} />;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript