json - 无法访问 json 对象的值?无法读取未定义的属性“company_about”?
问题描述
这是我的 JSON
[
{
"id": 1,
"job_id": 1,
"company_profile": "Sales and Marketing",
"company_about": "Established in 1992 , it is a renouned marketing company",
"company_product": "Ford,Mustang,Beetle",
"key_skills": "commmunication,english,spanish,german",
"qualification": "High School,Masters",
"job_description": "Must be a Local of Mumbai",
"created_at": null,
"updated_at": null
}
]
我试图获得它的价值。这是我记录它们的反应代码。
public getJobDetails = (jobid: number) => {
const JobId = jobid;
fetch('http://127.0.0.1:8000/api/jobs/detail/' + JobId)
.then(response => response.json())
.then(
responseJson => {
console.log(responseJson);
this.setState({ details: responseJson });
},
() => {
console.log(this.state.details);
}
)
.catch(error => {
console.error(error);
});
}
public render() {
const { details } = this.state;
console.log(details);
console.log(details[0]);
console.log(details[0]) 返回
{id: 1, job_id: 1, company_profile: "Sales and Marketing", company_about: "Established in 1992 , it is a renouned marketing company", company_product: "Ford,Mustang,Beetle", …}
但是为什么 console.log(details[0].company_profile) 返回 undefined ???它给出的错误是:
TypeError:无法读取未定义的属性“company_about”
谁能帮忙??
解决方案
在渲染中使用条件语句,这样如果您的请求未完成并且您的状态没有详细信息但它不会加载任何内容。
编辑---示例代码(不是您的应用程序,而是我的意思的概念)
从'react'导入反应,{组件,片段};
export class App extends Component {
constructor(){
super()
this.state = {
data: [],
isLoading: true
}
}
componentWillMount(){
this.fetchDetails()
}
fetchDetails = () =>{
fetch('/some/url')
.then(res => res.json())
.then( => {
this.setState({data, isLoading: false})
})
}
render() {
return (
<Fragment>
{!this.state.isLoading && <ChildComponent data={this.state.data}} />}
</Fragment>
);
}
}
推荐阅读
- node.js - Knex连接问题?EAI_AGAIN
- kofax - Kofax TotalAgility 数据库加入 TotalAgilityDocuments 数据库
- php - 无法访问安装了 wordpress 的 ec2 实例
- xodus - Xodus 中的子字符串或正则表达式搜索
- java - 我的模拟 junit5 不适用于我的子类
- cl.exe - 跟踪器:错误 TRK0005:未能找到:“CL.exe”。该系统找不到指定的文件
- c# - 将 WPF 窗口添加到 Winforms 应用程序时是否存在陷阱?
- javascript - 仅输出最后一个属性,而其他属性不输出
- flutter - 小部件 Flutter 的条件渲染
- mysql - 选择在所有考试中获得 A 的学生的信息