我有一个本地的json文件作为我的React应用的一部分。它的结构如下。
[
{
"id": 1,
"company": "Photosnap",
"logo": "./images/photosnap.svg",
"new": true,
"featured": true,
"position": "Senior Frontend Developer",
"role": "Frontend",
"level": "Senior",
"postedAt": "1d ago",
"contract": "Full Time",
"location": "USA Only",
"languages": ["HTML", "CSS", "JavaScript"]
},
{
"id": 2,
"company": "Manage",
"logo": "./images/manage.svg",
"new": true,
"featured": true,
"position": "Fullstack Developer",
"role": "Fullstack",
"level": "Midweight",
"postedAt": "1d ago",
"contract": "Part Time",
"location": "Remote",
"languages": ["Python"],
"tools": ["React"]
},
作为React应用的一部分,我有一个job list组件和一个job card组件。 我的想法是,工作卡将呈现这样的状态 所以我想做的是渲染卡片右侧的按钮,招聘卡的代码如下。
import React from 'react';
import CustomButton from '../../custom-button/custom.button.component';
import './job-card.styles.css';
const JobCard = ({company, position, postedAt, contract, location, logo, featured, new: newJob, languages}) => (
<div className="container">
<div className='card'>
<div className='companyName'>
<img src={logo} alt="logo" width="100" height="100"></img>
</div>
<div className='content'>
<div className='newFeatured'>
<h2>{company}</h2>
{ newJob ? <button className='myButton'>New!</button> : null }
{featured ? <button className='myDarkButton'>Featured</button> : null }
</div>
<h1>{position}</h1>
<div className='details'>
<h3>{postedAt} ·</h3>
<h3>{contract} ·</h3>
<h3>{location}</h3>
</div>
{languages.map((language) =>
<CustomButton>{language}</CustomButton>
)}
</div>
</div>
</div>
)
export default JobCard;
我的职位列表组件的代码是这样的:
import React from 'react';
import './job-listing.styles.css';
import JobCard from '../job-card/job-card.component.jsx/job-card.component';
import { Component } from 'react';
class JobListing extends Component {
constructor() {
super();
this.state = {
jobs: []
}
};
componentDidMount() {
fetch('/data.json')
.then(response => response.json())
.then(data => this.setState({jobs: data}))
}
render() {
return (
<div>
{this.state.jobs.map(({id,...otherJobProps}) =>(
<JobCard key={id} {...otherJobProps} />
))}
</div>
)
}
}
export default JobListing;
我得到的错误与卡片组件中的语言道具有关。 由于它是一个数组,我试图对它进行反结构化,但没有成功。希望得到任何帮助。
假设它是 map
你已经说过了,问题是,你至少有一个对象没有一个 languages
属性--例如,你接收的数据有时会将其忽略。你的示例JSON中的两个对象有这个属性,但显然,不是所有的对象都有。
如何处理它取决于你。
你可以在重构时默认它,通过添加 = []
之后 languages
在参数列表中的解构中。
const JobCard = ({company, /*...*/, languages = []) => (
你可以避免在参数列表中调用 map
在JSX中,当 languages
是假的。
{languages && languages.map((language) =>
<CustomButton>{language}</CustomButton>
)}
附注: key
财产上 CustomButton
你正在创建的 map
回调。