【发布时间】:2019-05-28 19:35:54
【问题描述】:
我已经从调用 Django Rest API 的地方响应 App.js 页面,并且我正在以数组的形式获得响应,现在这个数组我有嵌套组件,我希望在我的代码中列出该嵌套组件。
如果我在尝试处理多个记录时可以展示由单个人名给出的单个记录,则会出现以下错误。 警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”属性。
现在如果我更改 API URL 如下 https://e2isaop.rokuapp.com/api/perns/1
我可以在 HTML 中查看数据,但是当涉及到所有人时,它就失败了。
对不起,我是新手,不知道如何迭代结果的子数组。 请在此处指导我以获得最佳实践。
这是 JSON 格式的 API 响应
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"uri": "/api/Persons/1",
"PersonId": 1,
"PersonName": "Nirav Joshi",
"Person_Image": "https://ja.amazonaws.com/media/persons/None/51e1257926f3cb184089c41fa54b8f8e1b65a98f1e35d39e55f2b6b335e83cf4.jpg",
"Person_sex": "M",
"Person_BDate": "2019-04-19",
"Person_CDate": "2019-04-23"
},
{
"uri": "/api/Persons/2",
"PersonId": 2,
"PersonName": "New Joshi",
"Person_Image": "https://ja.amazonaws.com/media/persons/None/cc08baaad2ccc918bc87e14cac01032bade23a0733b4e313088d61ee78d77d64.jpg",
"Person_sex": "F",
"Person_BDate": "2011-11-21",
"Person_CDate": "2019-04-27"
},
]
}
这里是 react App.js 代码。
import React from "react";
import ReactDOM from "react-dom";
import Persons from "./Persons";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
persons: []
};
}
componentDidMount() {
fetch("https://e2isen.okuapp.com/api/psons/")
.then(response => response.json())
.then(data => {
let apipersons;
if (data.isNull) {
apipersons = [];
} else {
apipersons = [data];
console.log(apipersons);
}
this.setState({ persons: apipersons });
});
}
render() {
return (
<div>
<h1>Welcome to PersonAPI</h1>
<div>
{this.state.persons.map(pers => {
return (
<Persons
PersonName={pers.PersonName}
key={pers.PersonId}
Person_Image={pers.Person_Image}
Person_BDate={pers.Person_BDate}
Person_sex={pers.Person_sex}
/>
);
})}
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
它应该给我四个人的结果及其详细信息 人名 人物形象 人日期 性交
【问题讨论】:
-
console.log(response) 的结果是什么?作为响应,应该有一个数据,里面应该有一个结果数组。
-
你的数组应该是结果,而不是整个响应数据!
标签: javascript arrays reactjs django-rest-framework