gpt4 book ai didi

javascript - react.js 中的 Prop 问题

转载 作者:行者123 更新时间:2023-12-04 09:43:30 25 4
gpt4 key购买 nike

我是新来的 react 。我正在构建一个简单的联系人列表应用程序来显示联系人的姓名、电子邮件,我们将存储联系人的标语。我们将利用this ,它包含我们的联系人列表应用程序所需的数据的 JSON 转储。我有 2 个文件 statushelper.js 和 shape.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;

形状.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

有什么建议?

最佳答案

你正在渲染一个元素数组,所以 React 需要一个 key prop。

添加 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>
)
};

关于javascript - react.js 中的 Prop 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62226070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com