【问题标题】:is map function is not working or fetched data have some problem是地图功能不工作还是获取的数据有问题
【发布时间】:2022-01-18 22:11:56
【问题描述】:

在渲染列表时出现错误(无法读取未定义的属性(读取“地图”))。代码附在下面 请帮忙。 已获取并尝试呈现数据的 REACT 代码。

import React, { Component } from 'react'
// import axios from 'axios';
export default class List extends Component {
  constructor(props)
  {
    super(props);
    this.state={apiResponse:[]};
    
  }
callAPI()
  {
    fetch("http://localhost:9000/testAPI")  
    .then( (res) => res.json()) 
    .then( (data) => {this.setState({apiResponse: data.task});});
  }

  componentWillMount()
  {
    this.callAPI();
  }

  render() {
    return (
      <div>
          
        <h1>{this.state.apiResponse}</h1>
        {
            this.state.apiResponse.map((r)=>
                <li >r.task</li>
            )
        }
      </div>
    )
  }
}

从其中获取数据以做出反应的 NODE JS

router.get("/",function(req,res)
{

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("to-do");
    // var query = { address: "Park Lane 38" };
        dbo.collection("to-do").find({}).toArray(function(err, result) {
            if (err) throw err;
            console.log(result);
            res.json(result)
            // res.send((result))
            db.close();
        });
    });

   
})  

【问题讨论】:

  • 尝试在渲染方法中记录你的状态并在返回JSX之前检查你的状态是什么
  • 你的nodeJS-Function中console.log的输出是什么?它有一个名为“task”的属性吗?
  • 正在显示一个空数组,但是当将 res.json 转换为 res.text() 时,文本会在控制台中再次使用空数组轻松呈现。
  • 是的,它具有名为 task 的属性

标签: javascript node.js reactjs express


【解决方案1】:

您的问题是您的 json 响应不包括任务属性(至少不是每次都包含)。通过将 apiResponse 设置为该值,您将其设置为 undefined 并且 map-function 不再可用。一种解决方法是在设置状态之前检查属性任务是否可用。

fetch("http://localhost:9000/testAPI")  
    .then( (res) => res.json()) 
    .then( (data) => {
       if (data.task) {
          this.setState({apiResponse: data.task});
       }
    });

【讨论】:

  • 但是如果我们跳过任务属性并获取整个数据,那么在设置 res.text() 完美呈现时仍然显示相同的错误
  • 数据属性不是数组而是对象,据我所知,它没有映射方法。或者它也是未定义的?
猜你喜欢
  • 1970-01-01
  • 2018-10-06
  • 2011-05-06
  • 2011-04-06
  • 2012-06-02
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 2012-01-28
相关资源
最近更新 更多