UseEffect & Axios 获取有关将数据加载到 Card 的问题

UseEffect & Axios Get issues on loading data to Card

使用一个简单的卡片组件,我使用 UseEffect 从 API 使用 Axios 加载数据。目的是在组件加载的时候,给它加载一次数据。

问题是数据在加载时没有正确加载,而是在组件更新后重复加载。我怎样才能让它在页面加载时加载一次数据,而不是在加载页面之后加载数据?

我省略了 API url 但它已经过测试并且 returns 来自后端的数据正确。

卡片组件:

import React from 'react';
import { Card, CardImg, CardBody, CardTitle, CardSubtitle, Container, Row, Col } from 'reactstrap';

import { useEffect, useState } from "react";
import { APIGet } from '../API.js';


function RenderCardLoadMore() {
    const [data, setData] = useState([]);

    const resource = 'search';
    const params = { 'limit': '2' };
    const results = APIGet(resource, params);

    useEffect(() => {
        console.log("initialload");
        setData(results);
    }, []);

    return (
        <Container fluid>
            <Container>
                <Row>
                    {data.map((v, i) => (
                        <Col className="py-2" key={i} xs={12} md={4} lg={3}>
                            <Card className="explore_event_card shadow">
                                <CardBody>
                                    <CardTitle className="card_header">{v.Title}</CardTitle>
                                    <CardSubtitle>{v.SubTitle}</CardSubtitle>
                                </CardBody>
                            </Card>
                        </Col>
                    ))}
                </Row>
            </Container>
        </Container>
    );
}

export default RenderCardLoadMore;

API 分量:

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

const API_URL = 'https://myapi/'; /*url omitted for this question, tested and working*/

const session_id = localStorage.getItem("session_id");

export function APIGet (resource, params) {
    const [data, setData] = useState([]);
    const url = API_URL + resource;

    params['session_id'] = session_id;

    useEffect(() => {
        axios.get(url, {params: params}).then((v) => {
            setData(v.data)
        }).catch( (err) => console.log(["APIGet error:", err]) )
    }, [url]); //url as 2nd argument not needed?

    return data;
}

可以 删除 url 并使用空的依赖项数组,这样 useEffect 挂钩仅在初始渲染后触发一次。据我所知,APIGet 不需要成为一个挂钩,也不需要使用 useState 挂钩。我可以简单地 return 从 axios return 编辑 Promise 链。

API

import axios from 'axios';

const API_URL = 'https://myapi/.....';

export function APIGet (resource = "", params = {}) {
  const session_id = JSON.parse(localStorage.getItem("session_id"));
  const url = API_URL + resource;

  params['session_id'] = session_id;

  return axios.get(url, {params: params})
    .then((v) => {
      return v.data
    })
    .catch((err) => console.log(["APIGet error:", err]));
}

RenderCardLoadMore - 在 useEffect 挂钩中调用 APIGet 并在 Promise 解析时更新状态。

import { APIGet } from '../API.js';

function RenderCardLoadMore() {
  const [data, setData] = useState([]);

  const resource = 'search';
  const params = { 'limit': '2' };

  useEffect(() => {
    console.log("initialload");
    APIGet(resource, params)
      .then(results => {
        setData(results);
      });
  }, []);

  return (....);
}