Javascript Can’;t访问状态中存储的对象的属性
当我运行console.log(this.state.dossier)时,它返回具有许多属性的对象。但是当我运行console.log(this.state.dossier.code)时,它返回未定义的 如何渲染属性Javascript Can’;t访问状态中存储的对象的属性,javascript,reactjs,Javascript,Reactjs,当我运行console.log(this.state.dossier)时,它返回具有许多属性的对象。但是当我运行console.log(this.state.dossier.code)时,它返回未定义的 如何渲染属性 import React, { Component } from "react"; class Client extends Component { state = { dossier: [] }; componentDidMount = async ()
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;
import React,{Component}来自“React”;
类客户端扩展组件{
状态={
档案:[]
};
componentDidMount=async()=>{
const req=等待取数(`http://localhost:3000/api/dossier/EQDOM/D200074`);
const doss=await JSON.stringify(req);
this.setState({dossier:doss});
};
render(){
返回(
{this.state.docsier.length>0&&(
代码:{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`);
//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;
code
只能在this.state.docsier
的第一个索引上访问。看起来数据是一个数组,其中包含您正在查找的对象。
您应该通过以下方式访问它:
this.state.dossier[0].CODE
您必须使用这样的响应
=> this.state.dossier[0].CODE
因为您的代码类似于对象数组,并且代码是代码类型转换您确定其中包含“代码”吗?您可以检查网络请求并检查响应吗?没有人可以帮助您获得这些信息请发布您从
http://localhost:3000/api/dossier/EQDOM/D200074
也是。使用fetch()
incorrectly@AndrewL以下是数据:[{“ID”:34404198,“代理”:“1.1.9.”,“代码”:“EQDOM/D200074”,“DTCLOTURE”:null,“dtconstructiondp”:null,“DTCREATION”:null,“DT_INIT”:“2018-11-01T07:36:39.000Z”,“DT_MAJ”:“2018-12-03T23:00:00.000Z”,“DTMISEAJOUR”:null,“DTREMISEDOSSIER”:null,“usilizateur_ID”:568574,“indbcentralizationauto”:null,“noted卷宗”:null,“NUMARCHIVE”:null,“观测卷宗”:null,“组织ID”:70007,“STATUTDOSSIER”:null,“打字卷宗”:null}]@LucaFabbri即使只有很少的信息,它也应该工作并记录属性,但我不知道为什么它不工作
=> this.state.dossier[0].CODE