【问题标题】:How can I manage promise and map objects?如何管理 promise 和 map 对象?
【发布时间】:2021-10-28 20:48:37
【问题描述】:

我正在做一个项目,其中我的数据库中的数据是这样的:

我不明白我做错了什么!这是我的 FetchList.js

import { useState } from "react";


const FetchList = async()=>{

    const[data, setData] =  useState()
    const response = await fetch('https://__firebase__url__');
    
    if (!response.ok) {
        throw new Error("Something went wrong");
      }
  
      let responseData = await response.json();
      const loadedHospitals = [];
      for (const key in responseData){
        loadedHospitals.push({
          key: responseData[key].key,
          Name: responseData[key].Name,
          Email: responseData[key].Email,
          Contact_no: responseData[key].Contact_no,
          img: responseData[key].img,
        });
      }
      setData(loadedHospitals);
      const hospitals = data.map(hospital => {
        console.log(hospital);
       });
return data;
}
export default  FetchList;

我想将数组中的整个结果传递给 ListHospital.js,然后将其与 Card 组件进行映射。

import Card from "../UI/Card";
import FetchList from "./FetchList";
import { useState, useEffect } from "react";

const ListHospitals = () => {
    const [data, setData] = useState();

    useEffect(() => {
        FetchList().then(data => setData(data));
    }, []);
    
    return data.map((item)=><Card>{item}</Card>);
}

export default ListHospitals;

错误:

TypeError: Cannot read properties of undefined (reading 'map')

【问题讨论】:

  • 你有什么问题?
  • TypeError: data.map 不是函数@emkarachchi
  • useState({}) 有一个对象而不是数组
  • 是的,现在错误是TypeError: Cannot read properties of undefined (reading 'map')
  • 认为您需要从 FetchList 返回数据。尝试添加return loadedHospitals

标签: reactjs async-await react-props


【解决方案1】:

我认为您需要先将const [data, setData] = useState(); 写为const [data, setData] = useState([]);。因为 fetch list 是一个异步函数,所以它需要一些时间来获取你的数据,因此它会给你一个错误。您只能在数组上使用 map,并且在初始渲染期间,数据变量是 undefined

【讨论】:

  • 嘿@Mob_Abominator 我已经尝试过useState([ ])useState({ })useState(),但它对我没有用
【解决方案2】:

FetchingApp.js 等更高级别的查询解决了我的问题。 喜欢:-

function App() {
  const [ data, setData ] = useState([]);

  const fetching = async () => {
    const response = await fetch("_____url___");
    const responseData = await response.json();
    let loadedItem = [];
    for (const key in responseData) {
        loadedItem.push(responseData[key]);
    }
    console.log(loadedItem);
}
fetching();
  return (
    <>
      <h1>Hey</h1>
    </>
  );
}

export default App;

【讨论】:

    猜你喜欢
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多