javascript - 在 React 中仅显示来自 Rest api 的单个对象数组
问题描述
我试图在我的 React 应用程序中仅显示来自 rest api 的单个数组项,即带有标题对象的 Home 数组。但是我当前的代码显示了两次元素,是因为我在 Render 上通过它们进行映射吗?
到目前为止的代码:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
awsApiData: [],
};
}
componentDidMount() {
console.log('app mounted');
fetch('https://onelbip0e6.execute-api.eu-west-2.amazonaws.com/livestage/data')
.then(data => data.json())
.then(data => this.setState({awsApiData: data}, () => console.log(data)))
}
render() {
const data = this.state.awsApiData;
return (
<div>
{Object.keys(data).map(e => {
return <div>{data.home[0].title}</div>;
})}
</div>
);
}
}
render(<App />, document.getElementById('root'));
api 架构
{
"home": [
{
"title": "John Doe title",
"body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.",
"image": "image/example.jpg"
}
],
"about": [
{
"title": "John is the main part 1",
"body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.",
"image": "image/example.jpg"
}
]
}
解决方案
您正在调用的 API 的响应https://onelbip0e6.execute-api.eu-west-2.amazonaws.com/livestage/data
如下:
{
"home": [
{
"title": "John Doe title",
"body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.",
"image": "image/example.jpg"
}
],
"about": [
{
"title": "John is the main part 1",
"body": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.",
"image": "image/example.jpg"
}
]
}
您可以通过删除 Object.keys() 并从中映射来修改您的渲染方法,它将被修复,
render() {
const data = this.state.awsApiData;
return (
<div>
{(data && data.home) &&
<div>{data.home[0].title}</div>
}
</div>
);
}
推荐阅读
- python - PIL 照片图像不显示在 Tkinter 上
- python - 将数据帧的最后一行与它上面的一行和它上面的另一行进行比较
- c# - 在 GCR 上获取当前服务帐户
- amazon-web-services - AWS EC2 用户数据,多个 PowerShell 命令不起作用
- node.js - 发送带有云消息firebase通知的图像不起作用
- wordpress - Woocommerce 搜索结果
- angular - Angular Http Interceptor - fromPromise 错误 - TypeError: (0 , x.fromPromise) 不是函数
- typescript - 如何将打字稿类型声明为“变量”以供重复使用?
- javascript - 使用 sort 和 reduce 功能对 Object 的对象进行排序
- java - 在sqlite android中存储布尔值