javascript - 从 React.js 中的 json 文件中获取数据
问题描述
我有一个 json 文件调用 data.json 例如(我使用 React.js):
[{"id": 1,"title": "Child Bride"},
{"id": 2, "title": "Last Time I Committed Suicide, The"},
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"},
{"id": 4, "title": "Youth Without Youth"},
{"id": 5, "title": "Happy Here and Now"},
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"},
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"},
{"id": 8, "title": "Monty Python's The Meaning of Life"},
{"id": 9, "title": "Awakening, The"},
{"id": 10, "title": "Trip, The"}]
我的 componentDidMount 我有以下内容:
fetch('./data/data.json')
.then((response) => response.json())
.then((findresponse)=>{
console.log(findresponse.title)
this.setState({
data:findresponse.title,
})
})
}
在我的渲染中:
<ul>
<li> {this.state.title}</li>;
</ul>
我想列出我的 json 文件中的所有标题,
否则它说 .then((response) => response.json()) 是一个匿名函数。. .
如何解决这个问题?我有点困惑
非常感谢
解决方案
您可以使用异步/等待。它需要更少的代码行。
async getData(){
const res = await fetch('./data/data.json');
const data = await res.json();
return this.setState({data});
}
在 componentDidMount() 调用函数即
componentDidMount(){
this.getData();
}
最后,在渲染中,映射数据数组
render (){
return {<ul>{this.state.data.map(item => <li>{item.title}</li>)} </ul>
)
}
推荐阅读
- javascript - 无法将 javascript 添加到 chrome 扩展 html
- html - 如何在不影响顶部内容的情况下使背景图像模糊?
- javascript - 无法设置属性...未定义或空引用
- javascript - addeventlistener 后如何做到这一点不要覆盖 css 样式
- r - 如何添加这样的注释?
- sql - 如何从包含 oracle 模式中的列名的所有表中获取特定列的最大值?
- android - 在 ionic 3 中“找不到已安装的 Gradle 版本”
- cuda - 使用 Vulkan VkImage 作为 CUDA cuArray
- automated-tests - SoapUi 可以将任意消息发布到 JMS 队列吗?
- python - 如何将 Python 对象保存到 pymongo 中?(即我需要覆盖什么方法/返回值)