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

问题描述 投票:0回答:1

我想从 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 获取数据。有人知道为什么会发生吗?谢谢你的回答

reactjs react-hooks axios
1个回答
0
投票

问题出在你的 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;
© www.soinside.com 2019 - 2024. All rights reserved.