【问题标题】:How to display data from API endpoint using Axios and React如何使用 Axios 和 React 从 API 端点显示数据
【发布时间】:2019-09-15 21:07:46
【问题描述】:

我目前正在学习本教程 - https://appdividend.com/2018/11/11/react-crud-example-mern-stack-tutorial/#React_CRUD_Example

我已经替换了自己的 API,并且成功地创建了新记录。我现在正在尝试查看所有记录的列表,但出现以下错误

这是代码(教程代码的精确副本,API 链接除外)

import React, { Component } from "react"; import axios from "axios"; import TableRow from "./TableRow"; export default class Index extends Component { constructor(props) { super(props); this.state = { address: [] }; } componentDidMount() { axios .get("http://localhost:6505/api/v1/Address") // .then(res => console.log(res)) .then(response => { this.setState({ address: response.data }); }) .catch(function(error) { console.log(error); }); } tabRow() { return this.state.address.map(function(object, i) { return ; }); } render() {...}

如果我在 '.then(res => console.log(res))' 上方注释掉的行中添加,错误消息将不再显示并且页面呈现但没有任何数据 - 请参见页面下方的屏幕截图和安慰。我已经突出显示了新的错误消息,并且还突出显示了我想要显示的数据。

任何指针都非常感谢:)

【问题讨论】:

  • tabRow 在哪里被调用?
  • 你可以这样做。setState({address:response.data.results
  • @nivendha 嗨,tabRow 函数在 内的 "render(){ return(" 之后调用
  • @lovepreetsingh 谢谢,这确实让我想到了,但似乎没有任何区别。不过我会把它留在代码中,因为我觉得我可能有不止一个问题。
  • 您正在尝试映射不存在的东西。哟可以设置一个initialState地址=[]

标签: reactjs axios crud


【解决方案1】:

.map 函数仅适用于数组。

数据似乎不是您期望的格式。

您可以尝试安慰response.dataresponse.data.results

你能用this.setState({ address: response.data.results });替换this.setState({ address: response.data });

【讨论】:

  • 谢谢,我刚刚将代码更新为.then(res => console.log(res.data.results)),结果按预期显示在控制台中。
  • 那你能不能把this.setState({ address: response.data });换成this.setState({ address: response.data.results });
  • 哦,我刚刚删除了.then(res => console.log(res.data.results)) 代码行并保存了页面,现在数据正在显示!非常感谢
【解决方案2】:

您的数据在 response.data.results 中,因此将其更改为这个即可。

谢谢

【讨论】:

  • 这似乎解决了这个问题。谢谢
猜你喜欢
相关资源
最近更新 更多
热门标签