简体   繁体   English

Rest API React 和 AXIOS 在功能组件中

[英]Rest API React and AXIOS in functional component

I need to parse Rest API resposnes with JSON.我需要用 JSON 解析 Rest API 响应。 But when I use AXIOS in functional compoment it returns first empty array and then exact api response.data / after render.但是当我在功能组件中使用 AXIOS 时,它会返回第一个空数组,然后在渲染后返回精确的 api response.data /。 So return functions returns empty array but in the fact the data is there but after rendering所以返回函数返回空数组,但事实上数据在那里但在渲染之后

The api response 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"
}

And the component body和组件体

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控制台日志控制台日志

That is the expected behavior.这是预期的行为。 Your first console.log is being executed before the state update.您的第一个console.log在 state 更新之前执行。 The function is not returning an empty array, you're seeing the default state from const [eventDetails, setEventDetails] = useState([]) being logged. function 没有返回空数组,您会看到来自const [eventDetails, setEventDetails] = useState([])的默认 state 被记录。

Initially on the page load... you dont have data because API takes some moment before it respond with data and meanwhile your component already rendered with empty array ie no data...最初在页面加载时...您没有数据,因为 API 在响应数据之前需要一些时间,同时您的组件已经用空数组呈现,即没有数据...

at some moment later the API comes back with data and update the state but you've already seen a component without required data...稍后,API 会返回数据并更新 state,但您已经看到了一个没有所需数据的组件...

So a way around it is所以解决它的方法是

You put a component/content/loader to be shown while you're waiting for API to give you data to be shown... and when that data comes you take back the loader component and show that data from API在等待 API 为您提供要显示的数据时,您放置了一个要显示的组件/内容/加载器......当数据到来时,您收回加载器组件并显示来自 API 的数据

With codes it could be something as below使用代码可能如下所示

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 />}</>

Thanks guys.多谢你们。 Sometimes I have undefined errors.有时我有未定义的错误。 Now I understand why.现在我明白为什么了。 My function is called on every render.每次渲染都会调用我的 function。 So I added Loader所以我添加了加载器

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

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