[英]React Error TypeError: Cannot read property 'name' of undefined
I am learning to react but I am stuck in one issue.我正在学习做出反应,但我陷入了一个问题。 I am trying to get the array properties in my Useritem.js file
我正在尝试在我的 Useritem.js 文件中获取数组属性
this is my User.js file这是我的 User.js 文件
import React, { Component } from 'react'
import Useritems from './Components/Useritems';
const User = () => {
state = {
users: [
{ name: 'David', age: '20', Position: 'developer' },
{ name: 'Francis', age: '20', Position: 'Software Engineer' },
]
}
return (
<div>
{this.state.users.map(user => (
<Useritems user={user} />
))}
</div>
);
}
export default User
And this is my Useritem.js file这是我的 Useritem.js 文件
import React from 'react'
const Useritems = ({ user: { name, age, job } }) => {
return (
<div>
<h1>{name}</h1>
<h2>{age}</h2>
<h3>{job}</h3>
</div>
)
}
export default Useritems
But I am getting an error saying that the property name is not defined但我收到一条错误消息,指出未定义属性名称
You are using a functional component (as opposed to a class component), so you cannot use this.state
.您正在使用功能组件(而不是 class 组件),因此您不能使用
this.state
。 Instead you need to use the hook useState
to handle your state, which you can do like this:相反,您需要使用钩子
useState
来处理您的 state,您可以这样做:
import React, { useState } from "react";
import Useritems from "./Components/Useritems";
const initialUsers = [
{ name: "David", age: "20", Position: "developer" },
{ name: "Francis", age: "20", Position: "Software Engineer" }
];
const Users = () => {
const [users, setUsers] = useState(initialUsers);
return (
<div>
{users.map((user) => (
<Useritems key={user.name} user={user} /> // don't forget the key, though will want to find something more unique than name!
))}
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.