我是新来的反应者。我正在构建一个简单的联系人列表应用程序,以显示联系人的姓名,电子邮件,我们将存储联系人的标语。我们将使用this,它包含联系人列表应用程序所需的JSON数据转储。我有2个文件statushelper.js和shapes.js
下面是statushelper.js
import React, {Component} from 'react';
import Shapes from './Shapes';
class StatusHelper extends Component {
constructor() {
super();
this.state = {
contacts: []
};
}
componentDidMount() {
fetch('http://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then((data) => {
this.setState({contacts: data})
})
.catch(console.log)
}
render () {
return (
<Shapes contacts={this.state.contacts} />
);
}
}
export default StatusHelper;
Shapes.js
import React from 'react'
const Shapes = ({ contacts }) => {
return (
<div style={{text_align: 'center'}}>
<h1>Contact List</h1>
{contacts.map((contact) => (
<div className="card">
<div className="card-body">
<h5 className="card-title">{contact.name}</h5>
<h6 className="card-subtitle mb-2 text-muted">{contact.email}</h6>
<p className="card-text">{contact.company.catchPhrase}</p>
</div>
</div>
))}
</div>
)
};
export default Shapes
当我运行statushelper.js文件时,我遇到以下错误
'contacts' is missing in props validation react/prop-types
Missing "key" prop for element in iterator react/jsx-key
有什么建议吗?
这些不是错误,而只是警告。解决这些警告。执行以下操作:
1)您缺少道具类型,这就是您遇到第一个错误的原因。
在shapes.js
中执行此操作:
import PropTypes from 'prop-types';
// Component declaration
Shapes.propTypes = {
contacts: React.PropTypes.arrayOf(React.PropTypes.shape({
name: React.PropTypes.string,
email: React.PropTypes.string,
company: React.PropTypes.shape({
catchPhrase: React.PropTypes.string
})
}))
};
2)您缺少map
函数中对optimisation起作用的键:只需更改
{contacts.map((contact) => (
<div className="card">
到
{contacts.map((contact, index) => (
<div className="card" key={index}>
您正在渲染元素数组,所以React需要一个关键道具。
将index
添加到映射中,并将key={index}
添加到div“卡”中。像这样:
const Shapes = ({ contacts }) => {
return (
<div style={{text_align: 'center'}}>
<h1>Contact List</h1>
{contacts.map((contact, index) => (
<div className="card" key={index}>
<div className="card-body">
<h5 className="card-title">{contact.name}</h5>
<h6 className="card-subtitle mb-2 text-muted">{contact.email}
</h6>
<p className="card-text">{contact.company.catchPhrase}</p>
</div>
</div>
))}
</div>
)
};