首页 > 解决方案 > 在 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"
    }
  ]
}

标签: javascriptreactjs

解决方案


您正在调用的 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>
    );
  }

推荐阅读