使用 API 数据在 React.js 中创建 React Table

Using API data to create React Table in React.js

我之前看过一些使用 API 数据创建 React tables 的示例,但没有人使用 API 数据中的 header(key) 来设置 headers 反应 table。请有人帮我做这个。

在我的代码中,我从数组中的 API 数据中提取了 headers。然后我需要将列中的值作为 Headers 和访问器值传递。但是我不知道该怎么做。

这是 API = https://reqres.in/api/users?page=1

我正在钩子中从这个 Axios API 获取数据:

import axios from 'axios';
let userRole;
const [userData, setUserData] = useState({});

useEffect(()=>{

  axios.get(`https://reqres.in/api/users?page=1`)
  .then(res => {
      userRole = res.data.data;
      console.log("Data from API",userRole);
      userRole.sort((a,b) => a.first_name.localeCompare(b.first_name) )
      setUserData(userRole);
  });

}, []);

//console.log(userData);

API 来自 UserRole 的数据如下所示: enter image description here

let headerList = [];
function BasicTableComponent() {

          //console.log("Full data in array",userData)

          // EXTRACT VALUE FOR HTML HEADER. 
        for (var i = 0; i < userData.length; i++) {
            for (var key in userData[i]) {
                if (headerList.indexOf(key) === -1) {
                    headerList.push(key);
                }
            }
        }

        console.log("Column Header List check",headerList);

/*Now instead of this hardcoded method I want to pass values 
from my headerList for Header and accessor in my columns.*/

         const columns = React.useMemo(
            () => [
              {
                Header: 'Column 1',
                accessor: 'col1', // accessor is the "key" in the data
              },
              {
                Header: 'Column 2',
                accessor: 'col2',
              },
            ],
            []
          )

        //console.log("Column Header",columns)

        const {
            getTableProps,
            getTableBodyProps,
            headerGroups,
            rows,
            prepareRow,
          } = useTable({ columns, userData })

    return (

        <table {...getTableProps()} style={{ border: 'solid 1px blue' }}>
        <thead>
         {headerGroups.map(headerGroup => (
           <tr {...headerGroup.getHeaderGroupProps()}>
             {headerGroup.headers.map(column => (
               <th
                 {...column.getHeaderProps()}
                 style={{
                   borderBottom: 'solid 3px red',
                   background: 'aliceblue',
                   color: 'black',
                   fontWeight: 'bold',
                 }}
               >
                 {column.render('Header')}
               </th>
             ))}
           </tr>
         ))}
       </thead>
       <tbody {...getTableBodyProps()}>
         {rows.map(row => {
           prepareRow(row)
           return (
             <tr {...row.getRowProps()}>
               {row.cells.map(cell => {
                 return (
                   <td
                     {...cell.getCellProps()}
                     style={{
                       padding: '10px',
                       border: 'solid 1px gray',
                       background: 'papayawhip',
                     }}
                   >
                     {cell.render('Cell')}
                   </td>
                 )
               })}
             </tr>
           )
         })}
       </tbody>
     </table>
    )
}

据我了解,您要创建一个 objects 的数组,该数组具有两个属性。一个是 'column name',将用作 table 中的 header,第二个是 'key',用于访问 'userData' 中的值。

  1. 我已修改 useEffect 以检索数据、设置 userData 和设置列。

  2. 因为您希望列保存动态数据,所以我将该部分放在 useEffect 中,因为它依赖于我们从 API 检索的数据。抱歉没有正确格式化代码。

    const ParentComponent = (props) => {
     const [userData, setUserData] = useState({});
     const [loading, setLoading] = useState(false);
     const [columns, setColumns] = useState([]);
    
     const getData = async () => {
       await axios.get("https://reqres.in/api/users?page=1").then((resp) => {
       let data = resp.data.data.sort((a, b) =>
        a.first_name.localeCompare(b.first_name)
      );
       let cols = Object.keys(data[0]).map((key) => {
         return {
           Header: key.toUpperCase(),
           accessor: key
         };
       });
       setUserData(data);
       setColumns(cols);
       setLoading(false);
     }
    
    
    useEffect(() => {
     setLoading(true);
     getData();
    }, []);
    
    return(
     <TableComponent columns={columns} userData={userData} />
    )}