【问题标题】:React-Hooks: how to create dynamic reusable data table component?React-Hooks:如何创建动态可重用数据表组件?
【发布时间】:2021-03-31 00:44:30
【问题描述】:

在我的应用程序中,我需要可重用的数据表组件。我可以在哪里使用动态内容更改表头和表体。数据来自不同的 API。

//Table Component
 const Table = ({ headers, data }) => {
 return (
   <table>
     <thead>
       <tr>
         {headers.map(head => (
           <th>{head}</th>
         ))}
        </tr>
      </thead>
     <tbody>
      {data.map(row => (
        <tr>
          {headers.map(head => (
            <td>{row[head]}</td>
          ))}
        </tr>
       ))}
     </tbody>
    </table>


//app.js

 export default function App() {
 const headers = ["Name", "Age", "Country"];
 const data = [
   {
    Name: "Tom",
    Age: "10",
    Country: "India"
   },
  {
   Name: "Sam",
   Age: "33",
   Country: "USA"
  }
 ];

 return (
   <div>
   <Table headers={headers} data={data} />
   </div>
  );
  }

如何从不同的 API 动态数据?

【问题讨论】:

    标签: reactjs api react-hooks


    【解决方案1】:

    我们从 API https://stackblitz.com/edit/react-ie2rt6 获取数据

    import React, { useState, useEffect } from "react";
    import "./style.css";
    import Table from "./Table";
    import axios from "axios";
    
    export default function App() {
      const [headers, setHeaders] = useState([]);
      const [data, setData] = useState([]);
    
      useEffect(() => {
        const getPosts = async () => {
          const { data } = await axios.get(
            "https://jsonplaceholder.typicode.com/posts"
          );
          console.log(data);
          setData(data);
          setHeaders(Object.keys(data[0]));
        };
    
        getPosts();
      }, []);
    
      return (
        <div>
          <h1>Hello StackBlitz!</h1>
          <Table headers={headers} data={data} />
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2021-07-11
      • 2021-04-15
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多