首页 > 解决方案 > ReactJS:如何使用数组呈现 JSON 对象

问题描述

我正在尝试将带有数组的对象呈现为从 API 接收的数组(JSON)。我已经尝试了很多,但我没有得到解决方案。

这是我收到的对象格式:

{
    "catalogue": [
        [
            "shoes.txt",
            "trousers.txt",
            "tshirts.txt"
        ]
    ]
}

这是我用来调用 API 和渲染对象的代码:

import React, { Component } from "react";
import axios from "axios";

class Result extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
    };
  }

  componentDidMount() {
    const URL = "http://localhost/catalogue";
    fetch(URL)
      .then((response) => response.json())
      .then((data) => this.setState({ items: data }));
  }

  render() {
    const catalogue = this.state.items.catalogue;
    return <div>{catalogue}</div>;
  }
}

export default Result;

我唯一能在网上展示的是:

shoes.txttrousers.txttshirts.txt

我能得到的视图是这样的:

shoes.txt
trousers.txt
tshirts.txt

有人会帮我吗?提前致谢。

标签: reactjsapirest

解决方案


尝试这个:

import React, { Component } from "react";

class Result extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
    };
  }

  componentDidMount() {
    const URL = "http://localhost/catalogue";
    fetch(URL)
      .then((response) => response.json())
      .then((data) => this.setState({ items: data.catalogue[0] }));
  }


  render() {
    let catalogue = this.state.items.map((item, key) => (
      <li key={key}>{item}</li>
    ));
    return <ul>{catalogue}</ul>;
  }
}

export default Result;

注意这一行中的“[0]”:

.then((data) => this.setState({ items: data.catalogue[0] }));


推荐阅读