我无法在react中从axios响应中获取数据

wnvonmuf  于 2023-06-22  发布在  iOS
关注(0)|答案(1)|浏览(147)

我想从API获取数据,但我的数据不想从axios响应中获取。为什么会这样,因为在我用这种方法之前,它是确定的。
这是我的代码

import React, { useState, useEffect } from "react";
import { Link, useLocation } from 'react-router-dom';

import axios from 'axios';
// reactstrap components
import {
    Card,
    CardHeader,
    CardBody,
    CardFooter,
    CardTitle,
    Row,
    Col,
} from "reactstrap";

function Rooms() {
    const [rooms, setRooms] = useState([]);
    let { state } = useLocation();

    var data = []
    useEffect(() => {
        // Update the document title using the browser API
        let config = {
            method: 'get',
            maxBodyLength: Infinity,
            url: 'http://localhost:3003/getAllRoomById?kos_id=' + state.id,
            headers: {
                'x-access-token': localStorage.getItem('token')
            }
        };

        axios.request(config)
            .then((response) => {
                console.log("room",response.data);
                data = response.data
                setRooms(data)
            })
            .catch((error) => {
                console.log(error);
            });
        console.log("room1", rooms)
    }, [rooms]);
    console.log("room2", rooms)
    const listItems = rooms.map((kost) =>
        <Col lg="3" md="6" sm="6">
            <Card className="card-stats">
                <CardBody>
                    <Row>
                        <Col md="4" xs="5">
                            <div className="icon-big text-center icon-warning">
                                <i className="nc-icon nc-shop text-warning" />
                            </div>
                        </Col>
                        <Col md="8" xs="7">
                            <div className="numbers">
                                <p className="card-category">{kost.price}</p>
                                <CardTitle tag="p">{kost.number}</CardTitle>
                                <p />
                            </div>
                        </Col>
                    </Row>
                </CardBody>
                <CardFooter>
                    <hr />
                    <Link to={{ pathname: "/about", state: kost.id }}>
                        <div className="stats">
                            Masuk <i className="fas fa-regular fa-door-open" />
                        </div>
                    </Link>
                </CardFooter>
            </Card>
        </Col>
    );

    return (
        <>
            <div className="content">
                <Row>
                    {listItems}
                </Row>
            </div>
        </>
    );
}

export default Rooms;

如您所见,我可以从我的房间console.log中获取数据,但无法从room1和room2 console.log中获取数据。有人知道为什么会这样吗?谢谢你的回答

px9o7tmv

px9o7tmv1#

问题出在useEffect()上。每次rooms更改值时,它都会再次运行API调用。这是无限的,并且可能由于过度使用而超时。尝试在具有两个useEffect设置的项目中运行此示例。首先,您应该看到一个事实,只有当组件重新渲染时才会改变。另一个将是一个连续的猫的事实流。
为了便于演示,我向rooms数组添加值,而不是仅仅替换它。你应该看看它有多频繁地被这样称呼。
负载:

import axios from "axios";
import { useEffect, useState } from "react";

export const CatFacts = () => {
    const [rooms, setRooms] = useState([]);
    var data = []
    useEffect(() => {
        // Update the document title using the browser API
        let config = {
            method: 'get',
            url: 'https://catfact.ninja/fact',
        };

        axios.request(config)
            .then(({data}) => {
                setRooms([data, ...rooms])
            })
            .catch((error) => {
                console.log(error);
            });
    }, []);

    return <div>{rooms.map((room) => {
        return <div>{room.fact}</div>
    })}</div>
}
export default CatFacts;

关于房间变更:

import axios from "axios";
import { useEffect, useState } from "react";

export const CatFacts = () => {
    const [rooms, setRooms] = useState([]);
    var data = []
    useEffect(() => {
        // Update the document title using the browser API
        let config = {
            method: 'get',
            url: 'https://catfact.ninja/fact',
        };

        axios.request(config)
            .then(({data}) => {
                setRooms([data, ...rooms])
            })
            .catch((error) => {
                console.log(error);
            });

    }, [rooms]);

    return <div>{rooms.map((room) => {
        return <div>{room.fact}</div>
    })}</div>
}
export default CatFacts;

相关问题