反应错误类型错误:无法读取未定义的属性“名称”

时间:2021-02-12 19:33:50

标签: javascript reactjs

我正在学习做出反应,但我遇到了一个问题。我试图在我的 Useritem.js 文件中获取数组属性

这是我的 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

这是我的 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

但我收到一个错误消息,说未定义属性名称

1 个答案:

答案 0 :(得分:1)

您使用的是功能组件(而不是类组件),因此您不能使用 this.state。相反,您需要使用钩子 useState 来处理您的状态,您可以这样做:

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>
  );
};