【发布时间】:2020-01-11 18:09:01
【问题描述】:
我正在关注 MERN 堆栈教程,其中父组件 Dashboard 将一组对象从其自己的道具(在 mapStateToProps 之后)传递到另一个组件 Education。尝试在 Education 组件中遍历这个数组会给我上面提到的错误。请帮忙,教程似乎没有错误,我完全按照它,为什么会出现问题?
<Education education={profile.education}/>
(在 Dashboard.js 中传递道具)教育是对象配置文件中的对象数组,该对象配置文件是从状态映射的道具。 profile 属性在同一组件的其他行中使用,不会给出任何其他错误。
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);
【问题讨论】:
-
在某些时候
education属性可能是undefined。您可以链接到教程并包含更多代码吗?这个组件是如何被调用和使用的? -
您还需要添加其余代码。这还不足以知道真正的问题在哪里。初始状态对象是什么样的?
-
本教程是 Brad Traversy 在 Udemy 上的付费课程。 MERN stack 社交媒体项目课程。
标签: arrays reactjs dictionary undefined react-props