在渲染表格元素之前将获取的响应加载到变量中 – ReactJS

huangapple go评论58阅读模式
英文:

Load fetch response in variable before rendering Table element - ReactJS

问题

我对React相当新,正在尝试使用通过fetch请求检索到的变量填充自定义Table组件。问题是表格组件会立即渲染,而完成fetch请求需要额外的一两秒时间,表格不会自动更新,因为变量被更新。

以下是代码:

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请求就无法正常工作。是否有更简单的方法来实现我的目标吗?

谢谢。

英文:

I am fairly new to React and am attempting to fill a custom Table component with data from a variable that is retrieved through a fetch request. The problem is that the table component renders instantly, and it takes an extra second or two to finish the fetch request, and the table does not automatically update as the variable is updated.

Here is the code:

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

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

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

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

    return (
        &lt;div&gt;
            &lt;Table id=&quot;id&quot; columns={columns} data={data} title=&quot;Admin Queue&quot; /&gt;
        &lt;/div&gt;
    );
}

If I remove the async from the loadQueue() function then the fetch doesn't work properly. Is there a simpler way to do what I'm attempting to do?

Thank you.

答案1

得分: 0

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>
  );
}
英文:

useState is used to define and update state variables within a React component. In this specific case, it is used to store the fetched data and update the component's state when the data is loaded.

useEffect is used to run a side effect, such as fetching data or updating the DOM, after the component is mounted. In this specific case, it is used to call the loadQueue function once when the component is mounted, which fetches the data and updates the component's state.

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

huangapple
  • 本文由 发表于 2023年3月9日 23:53:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定