在呈现表元素之前在变量中加载获取响应- ReactJS

nzkunb0c  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(68)

我刚接触React,正尝试用通过获取请求检索到的变量中的数据填充自定义Table组件,问题是Table组件会立即呈现,需要额外的一两秒钟来完成获取请求,并且表不会随着变量的更新而自动更新。
下面是代码:

export default function AdminQueue() {
    const columns = [
        { path: "id",   name: "ID" },
        { path: "status", name: "Status" },
        { path: "date",  name: "Date" },
        { path: "submitter",   name: "Submitter" },
        { path: "action", name: "Action" },
        { path: "code",  name: "Code" },
    ];
    
    let data = [
        
    ];

    async function loadQueue() {
        const response = await fetch('http://localhost:8088/api/adminqueue/', {
            method: 'GET',
            credentials: 'include',
            mode: 'cors'
        });

        const json = await response.json();
        const queue = JSON.parse(json);

        for (var i = 0; i < queue.length; i++) {
            var j = queue[i];
            data.push({id: j["JobID"], status: j["Status"], date: j["Time"], submitter: j["Submitter"], action: j["Action"], code: j["Type"]})
            console.log(data);
        }
    }
    loadQueue();

    return (
        <div>
            <Table id="id" columns={columns} data={data} title="Admin Queue" />
        </div>
    );
}

如果我从loadQueue()函数中删除了async,那么fetch就不能正常工作了。有没有更简单的方法来完成我正在尝试做的事情?
谢谢你。

92vpleto

92vpleto1#

useState用于定义和更新React组件中的状态变量,在本例中,它用于存储获取的数据,并在加载数据时更新组件的状态。
useEffect用于在挂载组件后运行一个副作用,比如取数据或者更新DOM,在这个特定的情况下,它用于在挂载组件时调用一次loadQueue函数,取数据并更新组件的状态。

import { useState, useEffect } from 'react';
    
    export default function AdminQueue() {
      const columns = [
        { path: "id", name: "ID" },
        { path: "status", name: "Status" },
        { path: "date", name: "Date" },
        { path: "submitter", name: "Submitter" },
        { path: "action", name: "Action" },
        { path: "code", name: "Code" },
      ];
    
      const [data, setData] = useState([]);
    
      async function loadQueue() {
        const response = await fetch('http://localhost:8088/api/adminqueue/', {
          method: 'GET',
          credentials: 'include',
          mode: 'cors'
        });
    
        const json = await response.json();
        const queue = JSON.parse(json);
    
        const newData = queue.map(j => ({
          id: j.JobID,
          status: j.Status,
          date: j.Time,
          submitter: j.Submitter,
          action: j.Action,
          code: j.Type,
        }));
    
        setData(newData);
      }
    
      useEffect(() => {
        loadQueue();
      }, []);
    
      return (
        <div>
          <Table id="id" columns={columns} data={data} title="Admin Queue" />
        </div>
      );
    }

相关问题