reactjs - 使用 REACT.JS 从 JSON 文件中的获取请求中获取未定义的值
问题描述
我来自 Vue 环境我对此有点困惑,我读了一些与此类似的其他问题,但我无法使其工作,
为什么我不能回显从获取请求中获取的嵌套对象的值?
我console.log
之后setState
得到了值,但在渲染中是未定义的,
import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component {
constructor() {
super();
this.state = {
isLoading: true,
articles: {}
};
}
componentDidMount() {
this.setState({ loading: true });
fetch("./articles.json")
.then(response => response.json())
.then(result => {
this.setState({
isLoading: false,
article: result.blog.article
});
console.log(
"componentDidMount__this.state.article=",
this.state.article.link.title
); //this gets the value
})
.catch(error => {
console.error(error);
});
}
render() {
//let articleTitle;
// this gets error ----> console.log(this.state.article.link.title);
// because .link is undefined
// console.log(this.state.article);
// if (this.state.article !== "undefined") {
// console.log("wait what?..");
// if I changed the state in fetch why this stil
// articleTitle = this.state.article.link.title;
// } else {
// articleTitle = "";
// }
// I assign "this.state.article.link.title" to a variable so I can avoid the error,
//
return (
<div className="App">
{/*<h1>{articleTitle}</h1> */}
<h1>{this.state.article.link.title}</h1>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
文章.json
{
"blog": {
"article": {
"id": 1,
"title": " 1 lorem ipsum",
"description": "lorem ipsum",
"image": {
"desktop": "https://via.placeholder.com/900x500?text=desktop",
"tablet": "https://via.placeholder.com/600x400?text=tablet",
"mobile": "https://via.placeholder.com/320x320?text=mobile"
},
"link": {
"title": "lorem link",
"url": "#"
},
"author": {
"avatar": "https://via.placeholder.com/125x125?text=125x125",
"name": "lorem ipsum"
}
}
}
}
解决方案
似乎this.state.article.link.title
在this.state.article === undefined
.
解决方案是以更安全的方式检索this.state.article.link.title
。
这通常通过利用短路评估来实现。我还在下面的示例中使用了解构赋值和默认参数。
还建议分配默认值this.state
,尤其是在处理不确定数据时。
// Default `this.state`.
this.state = {
article: {link: {title: ''}},
articles: {},
isLoading: true,
}
// Safe retrieval of `title`.
const {article = {}} = this.state
const {link = {}} = article.link
const title = link.title || ''
推荐阅读
- gradle - 使用特定配置运行插件任务
- canvas - 将 THREE.CanvasTexture 与 WebGL 绘制的画布一起使用
- c - 次和 CLOCK_PER_SEC 计算错误的时间
- asp.net-core - 在 Web Api 中返回 json 对象的动态列表
- python - 尝试创建子图但不断收到 ValueError 消息
- sql - 具有嵌套数据的行的 Big Query 重复数据删除
- firebase - 为什么 Google Analytics Firebase 从不显示自定义事件的参数?
- python - 在python中比较字符串的嵌套列表理解理解
- reactjs - 有没有办法只制作 wordpress 标题字段文本或在 React 中解析它?
- java - 检查一个特定事件之后是另一个事件并使用 RxJava 发出成功