ajax - 在 React : How do I Map through JSON array of objects, setState() 中获取请求并追加?

标签 ajax reactjs fetch

此 API 返回对象的 JSON 数组,但我在 setState 和追加方面遇到了问题。大多数文档都包含带有键的 JSON 对象。我从 renderItems() 函数中得到的错误是: ItemsList.js:76 Uncaught TypeError: 无法读取未定义的属性“map”

在 ItemsList.js 中

import React, { Component } from "react";
import NewSingleItem from './NewSingleItem';
import { findDOMNode } from 'react-dom';

const title_URL = "https://www.healthcare.gov/api/index.json";

class ItemsList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // error: null,
      // isLoaded: false,
      title: [],
      url: [],
      descrip: []
    };
  }

  componentDidMount() {
    fetch(title_URL)
      .then(response => {
        return response.json();
      })
      .then((data) => {
        for (let i = 0; i < data.length; i++) {
          this.setState({
            title: data[i].title,
            url: data[i].url,
            descrip: data[i].bite,
          });
          console.log(data[i])   
        }

      })
      .catch(error => console.log(error));
  }

  renderItems() {
    return this.state.title.map(item => {
      <NewSingleItem key={item.title} item={item.title} />;
    });
  }

  render() {
    return <ul>{this.renderItems()}</ul>;
  }
}

export default ItemsList;

上面,我试图通过项目进行映射,但我不太清楚为什么我不能通过我在 setState() 中设置的对象进行映射。注意:即使在我的 setState() 中使用 title: data.title,它也不起作用。有人可以解释我在哪里出错了吗?谢谢。

在 App.js 中

import React, { Component } from "react";
import { hot } from "react-hot-loader";
import "./App.css";
import ItemsList from './ItemsList';

class App extends Component {
  render() {
    return (
      <div className="App">
        <h1> Hello Healthcare </h1>
        <ItemsList />
        <article className="main"></article>
      </div>
    );
  }
}

export default App;

在 NewSingleItem.js 中

import React, { Component } from "react";

const NewSingleItem = ({item}) => {
  <li>
    <p>{item.title}</p>
  </li>
};

export default NewSingleItem;

最佳答案

问题是这一行:

this.setState({
  title: data[i].title,
  url: data[i].url,
  descrip: data[i].bite,
});

当你声明 this.state.titledata[i].title 时,它不再是一个数组。您需要确保它保持一个数组。您可能不想将它们分开,只需将它们全部保存在一个独立的数组中即可:

this.state = {
  // error: null,
  // isLoaded: false,
  items: [],
};

...


componentDidMount() {
  fetch(title_URL)
    .then(response => {
      return response.json();
    })
    .then((data) => {
      this.setState({
        items: data.map(item => ({
            title: item.title,
            url: item.url,
            descrip: item.bite,
        })
      });
      console.log(data[i])   
    }
  })

...

renderItems() {
  return this.state.items.map(item => {
    <NewSingleItem key={item.title} item={item.title} />;
  });
}

关于ajax - 在 React : How do I Map through JSON array of objects, setState() 中获取请求并追加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53244476/

相关文章:

php - Mysql fetch - 带有 HTML 链接的结果指向表 ID

javascript - 我的函数仅适用于我的 ajax 调用后的警报

javascript - 使用该选项的 id 获取 select2 的选定选项

jquery - React 教程 - 为什么在 ajax 调用中绑定(bind)它

javascript - React js中防止事件冒泡 'ineffective'

javascript - 获取错误: invalid json response body at reason: Unexpected end of JSON input when using mockfetch with Jest

javascript - 使用 jqgrid 进行内联编辑。我卡住了

javascript - 无法将内容附加到 FormData()

node.js - 无法加载资源 : the server responded with a status of 405 (Not Allowed) needs help on nginx. conf

php - 如何在没有 FETCHALL 的情况下在 MYSQL PDO 中获取 2 次