【问题标题】:Rest API React and AXIOS in functional component在功能组件中休息 API React 和 AXIOS
【发布时间】:2021-11-28 20:23:33
【问题描述】:

我需要用 JSON 解析 Rest API resposnes。但是当我在功能组件中使用 AXIOS 时,它首先返回空数组,然后在渲染后返回精确的 api response.data /。所以返回函数返回空数组,但事实上数据在那里,但在渲染之后

API 响应

{
"eventId": "3c6a12e3-ac96-4f9d-9d26-7c7a6c730198",
"organizerId": "23a41cd1-e60e-41ff-b5d3-13815ed9b3a9",
"eventDate": "2021-11-28T14:14:16.191167",
"eventPlayerLimit": 10,
"eventFee": 0.0,
"playerSubscriptions": [
{
"subscriptionId": "2616720f-7106-429e-89f6-97be51dfbaf6",
"subscriptionPaymentDone": "true",
"subscriptionDate": "2021-11-28T14:14:16.217146",
"subscriptionApproved": "true",
"eventTitle": "Title",
"eventDate": "2021-11-28T14:14:16.191167",
"playerId": "a04d3ca2-af3d-4655-9eaf-6a892efe2dab",
"playerEmail": "player@player.com"
}
],
"title": "Title"
}

还有组件体

import React, {Component, useEffect, useState} from "react";
import {Card, Button, Table} from "react-bootstrap";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCoffee } from '@fortawesome/free-solid-svg-icons'
import axios from "axios";
import {useParams} from "react-router-dom";

function EventsDetails () {
  const [eventDetails, setEventDetails] = useState([])
    let {id} = useParams();
    function getEvents() {
        axios.get("http://localhost:8080/api/events/"+id)
            .then(response => response.data)
            .then((data) => {
                setEventDetails(data)
            });
    }
    useEffect(()=>{
        getEvents();
    },[])
    console.log(id);
    console.log(eventDetails);
        return (
            <Card className={"border border-dark bg-dark text-white"}>
                <Card.Header><FontAwesomeIcon icon={faCoffee} /> Events</Card.Header>
                <Card.Body>
                    <Table bordered hover striped variant="dark">
                        <thead>
                        <tr align="center">
                            <th>Event Date</th>
                            <th>Event title</th>
                            <th>Localization</th>
                            <th>Payment Fee</th>
                            <th>Subscribed users</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        {eventDetails.length === 0 ?
                            <tr align="center">
                                <td colSpan="6">No events available</td>
                            </tr> :
                            <tr align="center">
                            <td colSpan="6">{eventDetails.length}</td>
                            </tr>
                        }
                        </tbody>
                    </Table>
                </Card.Body>
            </Card>
)
}export default EventsDetails

控制台日志

【问题讨论】:

  • 您的问题是什么?这是预期的行为:请求是异步的,不会阻塞组件渲染
  • 当您调用 api 时,数据在 http 请求完成之前不可用。出于这个原因,有一段时间数据不可用(第一次渲染)。当数据来自 API 调用时,另一个渲染完成,其中 eventDetail 状态填充了响应。

标签: javascript reactjs axios


【解决方案1】:

这是预期的行为。您的第一个 console.log 正在状态更新之前执行。该函数没有返回一个空数组,您会看到 const [eventDetails, setEventDetails] = useState([]) 的默认状态正在被记录。

【讨论】:

    【解决方案2】:

    最初在页面加载时...您没有数据,因为 API 在响应数据之前需要一些时间,同时您的组件已经用空数组呈现,即没有数据...

    稍后 API 会返回数据并更新状态,但您已经看到组件没有所需数据...

    所以解决它的方法是

    您在等待 API 为您提供要显示的数据时放置了要显示的组件/内容/加载器......当数据到来时,您收回加载器组件并显示来自 API 的数据

    使用代码可能如下所示

    import React, {Component, useEffect, useState} from "react";
    import {Card, Button, Table} from "react-bootstrap";
    import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
    import { faCoffee } from '@fortawesome/free-solid-svg-icons'
    import axios from "axios";
    import {useParams} from "react-router-dom";
    
    function EventsDetails () {
      const [eventDetails, setEventDetails] = useState([])
      const [isLoading, setIsLoading] = useState(false);
        let {id} = useParams();
        function getEvents() {
            setIsLoading(true);
            axios.get("http://localhost:8080/api/events/"+id)
                .then(response => response.data)
                .then((data) => {
                    setEventDetails(data)
                    setIsLoading(false);
                });
        }
        useEffect(()=>{
            getEvents();
        },[])
        
        ....//removed for brevity
    
        return <>{isLoading ? <DisplayLoader /> : <DisplayData />}</>
    

    【讨论】:

      【解决方案3】:

      谢谢各位。有时我有未定义的错误。现在我明白为什么了。每次渲染都会调用我的函数。所以我添加了加载器

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 2021-06-14
        • 2018-09-16
        • 2020-12-22
        • 2020-08-12
        • 2019-08-06
        • 2021-08-06
        • 2020-10-13
        相关资源
        最近更新 更多