当我console.log(this.state.dossier)时,它返回具有很多属性的对象。但是当我console.log(this.state.dossier.code)时,它返回的是未定义的。
如何渲染属性?
import React, { Component } from "react";
class Client extends Component {
state = {
dossier: []
};
componentDidMount = async () => {
const req = await fetch(`http://localhost:3000/api/dossier/EQDOM/D200074`);
const doss = await JSON.stringify(req);
this.setState({ dossier: doss });
};
render() {
return (
<div className="container">
{this.state.dossier.length > 0 && (
<div>
<span>code: {this.state.dossier.code}</span>
</div>
)}
</div>
);
}
}
export default Client;
答案 0 :(得分:0)
应该是这样的:
import React, { Component } from "react";
class Client extends Component {
state = {
dossier: []
};
componentDidMount = async () => {
const req = await fetch(`http://localhost:3000/api/dossier/EQDOM/D200074`);
//Remove JSON.stringofy since it will convert your object or array into a string;
// const doss = await JSON.stringify(req);
this.setState({ dossier: doss });
};
render() {
return (
<div className="container">
{this.state.dossier.length > 0 && (
<div>
<span>code: {this.state.dossier.map(data => data['code' || 'CODE'])}</span>
</div>
)}
</div>
);
}
}
export default Client;
由于您拥有这样的数据:
{
"ID":34404198,
"AGENCE":"1.1.9.",
"CODE":"EQDOM/D200074",
"DTCLOTURE":null,
"DTCONSTITUTIONDP":null,
"DTCREATION":null,
"DT_INIT":"2018-11-01T07:36:39.000Z",
"DT_MAJ":"2018-12-03T23:00:00.000Z",
"DTMISEAJOUR":null,
"DTRECEPTIONPIECES":null,
"DTREMISEDOSSIER":null,
"UTILISATEUR_ID":568574,
"INDBCENTRALISATIONAUTO":null,
"INDCLOTURE":null,
"NOTEDOSSIER":null,
"NUMARCHIVE":null,
"OBSERVATIONDOSSIER":null,
"ORGANISATION_ID":70007,
"STATUTDOSSIER":null,
"TYPEDOSSIER":null
}
CODE
仅可在this.state.dossier
的第一个索引上访问,现在您需要对其进行迭代。
答案 1 :(得分:0)
看起来数据是一个数组,其中包含要查找的对象。 您应该通过以下方式访问它:
this.state.dossier[0].CODE
答案 2 :(得分:0)
您必须使用这样的响应方式。
=> this.state.dossier[0].CODE
因为您就像对象数组,并且代码是CODE类型转换