繁体   English   中英

Rest API React 和 AXIOS 在功能组件中

[英]Rest API React and AXIOS in functional component

我需要用 JSON 解析 Rest API 响应。 但是当我在功能组件中使用 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

控制台日志控制台日志

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

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

稍后,API 会返回数据并更新 state,但您已经看到了一个没有所需数据的组件...

所以解决它的方法是

在等待 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 />}</>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM