如何将数据绑定到反应表

时间:2021-04-11 19:04:48

标签: javascript reactjs typescript html-table

我是第一次玩 React,我想连接(ID、名称、状态和数量):

import React from "react";
import { getGoods } from "./data";

export const Abc: React.FC = () => {
  return (
    <table className="table table-striped table-hover">
      <thead>
        <tr>
          <th scope="col">ID</th>
          <th scope="col">Name</th>
          <th scope="col">Status</th>
          <th scope="col">Quantity</th>
        </tr>
      </thead>

      <tbody>
        
      </tbody>

    </table>
  );
};

到表体:

SELECT TO_CHAR(indate, 'YYYY-MM-DD HH24:MI:SS') FROM RENTING 

顶部的樱桃也将与排序有关(例如,按照以下顺序:准备好、未准备好、待定)。

感谢您的帮助或提示!

这里是沙盒:

https://codesandbox.io/s/recursing-torvalds-c343o

3 个答案:

答案 0 :(得分:1)

加载数据

React 中的一切都围绕着状态原则。您想使用 useState 钩子将货物存储在 state 中。

const [goods, setGoods] = React.useState<Goods[]>([]);

您将使用 useEffect 挂钩加载数据,并在解决 Promise 后将其保存到组件状态。您希望一个空的依赖数组 [] 只运行一次效果。

React.useEffect(() => {
  // need to define the function and call it separately
  const load = async () => {
    try {
      const data = await getGoods();
      setGoods(data);
    } catch (error) {
      // your Promise won't ever error, but an actual API might
    }
  };
  load();
}, []);

在您的表格中,您遍历 goods 数组并为每个数组呈现一个表格行 trmap 回调中的元素应具有唯一的 key 属性,因此我使用 id 作为键。表格单元格 td 应遵循与列相同的顺序。

<tbody>
  {goods.map((item) => (
    <tr key={item.id}>
      <td>{item.id}</td>
      <td>{item.name}</td>
      <td>{item.status}</td>
      <td>{item.quantity}</td>
    </tr>
  ))}
</tbody>

排序

为了排序,您需要额外的状态来存储排序属性和排序顺序(升序或降序)。也许是这样的:

const [sortProperty, setSortProperty] = React.useState<keyof Goods>("id");

const [isDesc, setIsDesc] = React.useState(false);

点击您的列标题会更新这些状态。您可以将 sortPropertyisDesc 的当前值应用到您的 goods 数组,以便在呈现之前获得一个有序数组。

也许我们想再次单击当前排序列时要颠倒顺序,但在单击不同列时使用升序作为第一个排序。我们可以创建一个这样的函数,我们可以将其用作 onClick 元素的 th 处理程序。

const handleColumnClick = (name: keyof Goods) => {
  const isCurrent = sortProperty === name;
  setSortProperty(name);
  setIsDesc(prev => isCurrent ? !prev : false);
}
<th scope="col" onClick={() => handleColumnClick("id")}>ID</th>

要申请订单,我们可以从lodash's orderBy function获得帮助。

const order = isDesc ? "desc" : "asc";
const rows = orderBy(goods, sortProperty, order);

我们想在 rows 中使用这个有序变量 tbody 而不是无序的 goods


组件代码

Working Demo on CodeSandbox

import React from "react";
import { getGoods, Goods } from "./data";
import { orderBy } from "lodash";

export const Question3: React.FC = () => {
  const [goods, setGoods] = React.useState<Goods[]>([]);

  const [sortProperty, setSortProperty] = React.useState<keyof Goods>("id");
  const [isDesc, setIsDesc] = React.useState(false);

  const handleColumnClick = (name: keyof Goods) => {
    const isCurrent = sortProperty === name;
    setSortProperty(name);
    setIsDesc((prev) => (isCurrent ? !prev : false));
  };

  React.useEffect(() => {
    // need to define the function and call it separately
    const load = async () => {
      try {
        const data = await getGoods();
        setGoods(data);
      } catch (error) {
        // your Promise won't ever error, but an actual API might
      }
    };
    load();
  }, []);

  const order = isDesc ? "desc" : "asc";
  const rows = orderBy(goods, sortProperty, order);

  return (
    <table className="table table-striped table-hover">
      <thead>
        <tr>
          <th scope="col" onClick={() => handleColumnClick("id")}>
            ID
          </th>
          <th scope="col" onClick={() => handleColumnClick("name")}>
            Name
          </th>
          <th scope="col" onClick={() => handleColumnClick("status")}>
            Status
          </th>
          <th scope="col" onClick={() => handleColumnClick("quantity")}>
            Quantity
          </th>
        </tr>
      </thead>
      <tbody>
        {rows.map((item) => (
          <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.name}</td>
            <td>{item.status}</td>
            <td>{item.quantity}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

您在沙箱中混淆了默认导出和命名导出时出错。应该是:

import {Question3 as Abc} from "./Table";

您还需要export interface Goods 文件中的 data.ts 才能在您的组件中使用该类型。

答案 1 :(得分:0)

在你的表体中做类似的事情

<div className="table">
       {getGoods.data.map(goods=>(
           <tr>
               <td>{goods.id}</td>
               <td>{goods.name}</td>
               <td>{goods.status}</td>
                <td>{goods.quantity}</td>
           </tr>
       )
       )
       }
    </div>

答案 2 :(得分:0)

getGoods 是承诺,需要时间来解决。直到那时显示加载程序。

export const Abc: React.FC = () => {

const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
useEffect(() => {
    setLoading(true);
    (async () => {
        const dataResponse = await getGoods();
        setData(dataResponse);
    })().catch((e) => {
        console.error(e)
    }).finally(() => {
        setLoading(false);
    })
},[])
return (
    <table className="table table-striped table-hover">
        <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">Name</th>
                <th scope="col">Status</th>
                <th scope="col">Quantity</th>
            </tr>
        </thead>

        <tbody>
            {loading && <tr>
                <td colSpan='3'>Loading....</td>
            </tr>}
            {data.map(goods => (
                <tr>
                    <td>{goods.id}</td>
                    <td>{goods.name}</td>
                    <td>{goods.status}</td>
                    <td>{goods.quantity}</td>
                </tr>
                ))}
            </tbody>
        </table>
    );
};

这将帮助您确保在

中获得 finalData
const [data, setData] = useState([]);

我们如何从承诺中获取数据?使用

useState(handler, []) // [] so that is get called only once per component
const dataResponse = await getGoods(); // wait till promise resolves
相关问题