我是Java和React的新手。该代码显示错误,可以进一步改进该代码。有什么建议么?请抽象我要实现它。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
export class Projects extends Component {
static propTypes = {
projects: PropTypes.array.isRequired
};
render() {
const { projects } = this.props;
return (
<div className="projects container">
<Link to="/projects/new" className="btn">
New project
</Link>
{projects.map(project => (
<div>
<span className="language origin">
{project.languageFrom}
</span>
<span className="language destination">
{project.languageTo}
</span>
</div>
)}
</div>
);
}
};
答案 0 :(得分:0)
在执行.map之前,您需要进行条件检查。同样不要忘了在循环渲染顶部元素时将唯一键添加到顶部
{Array.isArray(projects) && projects.map((project,index) => (
<div key={"Key-"+index}>//or if each project contains unique I’d then add id as key instead of index like key={project.id}
<span className="language origin">
{project.languageFrom}
</span>
<span className="language destination">
{project.languageTo}
</span>
</div>
)}
答案 1 :(得分:0)
我认为语法有问题。尝试一下
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
export class Projects extends Component {
static propTypes = {
projects: PropTypes.array.isRequired
};
render() {
const { projects } = this.props;
return (
<div className="projects container">
<Link to="/projects/new" className="btn">
New project
</Link>
{projects.map(project => (
<div>
<span className="language origin">
{project.languageFrom}
</span>
<span className="language destination">
{project.languageTo}
</span>
</div>
))}
</div>
);
}
}