类型错误:无法读取未定义的属性“map”,是否无法将数组作为props传递给功能组件?

IT技术 arrays reactjs dictionary undefined react-props
2021-05-22 12:07:41

我正在关注一个 MERN 堆栈教程,其中父组件仪表板将一组对象从它自己的props(在 mapStateToProps 之后)传递到另一个组件 Education。尝试在 Education 组件中迭代这个数组给了我上面提到的错误。请帮忙,教程似乎没有错误,我完全遵循了它,为什么会出现问题?

<Education education={profile.education}/>

(在 Dashboard.js 中传递props)教育是对象配置文件中的一组对象,它是从状态映射的props。profile prop 用在同一组件的其他行中,不会给出任何其他错误。

const Education = ({education}) => {
    const educations = education.map(edu => (
    <tr key={edu._id}>
        <td>{edu.institute}</td>
        <td>{edu.course}</td>
        <td>
        <Moment format='YYYY/MM/DD'>{edu.from}</Moment - <Moment 
         format='YYYY/MM/DD'>{edu.to}</Moment>
        </td>
        <td className="btn brick">
            Delete
        </td>
    </tr>
    ));

     ...return block with JSX that renders when {educations} is omitted
}

(尝试在 Education.js 中迭代)

编辑:完整的 Dashboard.js 代码

import React ,{Fragment,useEffect} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
import {getCurrentProfile} from '../../actions/profile';
import Spinner from '../layouts/Spinner';
import DashboardActions from './DashboardActions';
import Education from './Education';

const Dashboard = ({getCurrentProfile, auth, profile}) => {

useEffect(() => {
    getCurrentProfile();
}, []);


return (
    profile.loading && profile.profile === null ? <Spinner /> : <Fragment>
        <h1 className="large text-primary">Dashboard</h1>
        <p className="lead">Welcome {auth.user && auth.user.name }</p>
        {profile.profile !== null
        ?
        <Fragment>
            <DashboardActions/>
            <Education education={profile.education}/>
        </Fragment>
        : 
        <Fragment>
            <p>You have not yet set up a profile, please add some 
information about yourself</p>
            <Link to="/create_profile" className="btn btn-primary">Create 
Profile</Link>
        </Fragment>}
    </Fragment>
    );
}

Dashboard.propTypes = {
getCurrentProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
profile: PropTypes.object.isRequired,
}

const mapStateToProps = state => ({
auth: state.auth,
profile: state.profile
});

export default connect(mapStateToProps, {getCurrentProfile})(Dashboard);
2个回答

你有没有尝试console.log(education)看到教育的value?

我认为是undefined在加载配置文件时。

你可以试试 const educations = education && education.map(edu => (

我有一个类似的问题,我被困了很长时间。

我的原因非常模糊,但我正在导入一个对象History,我会将 PropType 对象传递给该对象。

然后history我在我的Progress对象中创建了一个 PropType ,我在 propTypes 对象中定义了它。

import History from "../components/class/History";
...
const Progress = ({ history, ...
...
    <History data_in={history}/>
...
Progress.propTypes = {
  history: PropTypes.object.isRequired,
...

History作为 PropType 创建导入和历史记录的冲突导致对象以History未定义的形式传入,因此.map正在对未定义的对象调用。

我不确定是否有人会设法复制它,但它可以帮助某人。:)