如何确保我的用户对象列表遵循反应表的列列表

问题描述 投票:0回答:1

大家好,我想和你们谈谈我正在尝试做的事情。简而言之,我使用 React 创建了一个 HTML 表格,将 Table.js 分为两个组件,例如: StaffColumns.js StaffData.js 在这两个函数中,我们有传递 props 的函数,即:

StaffData.js

//utentiLista it's my list of objects inside an Array called "utentiLista"
const StaffDati = ({utentiLista}) => {
    
  const styleText = {
    backgroundColor: '#1F2A37',
    textAlign: 'left',
    padding:'10px 10px 10px 10px',
    color: 'var(--primary-text)',
    paddingLeft: '10px',
    borderTop: '1px solid #343E4E',
    borderBottom: '1px solid #343E4E',
  }


    const getStatusStyle = (status) => {
        switch (status) {
          case 'Completed':
            return ({ color: 'lightgreen',
                      src: check
            });
          case 'Pending':
            return { color: 'yellow',
                      src: hour
          };
          case 'In progress':
            return { color: '#A992F6',
                      src: cloud
          };
          default:
            return {};
        }
      };
      
    return (
        <tbody style={{width:'100%'}}>
      {//! la lista utenti viene passata come props a Tabella e poi fatto un mapping proprio come in Sidebar.js
      
      utentiLista.map((utente, index) => (
        
      <tr key={utente.id} style={{width:'100%'}}>
        <td style={{...styleText, borderLeft: index === -1  ? 'none' : '1px solid #343E4E'}}>{utente.id}</td>
        <td style={styleText}>{utente.username}</td>
        <td style={styleText}>{utente.data}</td>
        <td style={styleText}>{utente.amount}€</td>
        <td style={{...styleText, borderRight: index === utentiLista.length  ? 'none' : '1px solid #343E4E' }}>

          <div style={{color: getStatusStyle(utente.status).color, 
                       width: 'fit-content', 
                       padding:'5px', 
                       border:`1px solid ${getStatusStyle(utente.status).color}`, 
                       borderRadius: '10px', 
                       fontSize: '10px',
                       backgroundColor: '#374151',
                       display: 'flex',
                       flexDirection: 'row', 
                       flexWrap: 'no-wrap',
                       alignContent: 'center', 
                       gap: '5px'}}>
                        <img src={getStatusStyle(utente.status).src} alt="" />
          {utente.status}
          </div>
          </td>
      
      </tr>
      ))}
    </tbody>
    )
    
}

export default StaffDati; 

我的 StaffColumns 有以下代码:

import React, {useState, useTransition } from "react"
const ColoneStaff = ({utentiLista, setUtentiLista}) => {
    
    const styleTr = {
        backgroundColor: '#374151',
        color: 'var(--primary-text)',
        textAlign: 'left',
      }
      const styleTh = {
        backgroundColor: '#374151',
        color: 'var(--primary-text)',
        textAlign: 'left',
        padding: '20px 0px 20px 10px',
        cursor: 'pointer',
      };
      const [staffColumns, setStaffColumns] = useState([
        {
        name: 'ID',
        field: 'id',
        type: 'number',
        style: styleTh,
        ascending: true,
        isSortable: true,
      },
      {
          name: 'Username',
          field: 'username',
          type: 'string',
          style: styleTh,
          ascending: true,
          isSortable: true,
      },
      {
          name: 'Data',
          field: 'data',
          type: 'string',
          style: styleTh,
          ascending: true,
          isSortable: false,
      },
      {
          name: 'Amount',
          field: 'amount',
          type: 'number',
          style: styleTh,
          ascending: true,
          isSortable: true,
      },
      {
          name: 'Status',
          field: 'status',
          type: 'string',
          style: styleTh,
          ascending: true,
          isSortable: true,
      },
      {
        name: 'Action',
        field: 'action',
        type: 'string',
        style: styleTh,
        ascending: true,
        isSortable: false,
      }
      
    ]);
    const handleSort = (field) => {
      const sortingColumn = staffColumns.find((column) => column.field === field);
      if (field) {
        const updatedColumns = staffColumns.map((column) => {
          if (column.field === field && column.isSortable) {
            column.ascending = !column.ascending;
          }
          return column;
        });
  
        setStaffColumns(updatedColumns);
  
        const sortedList = [...utentiLista].sort((a, b) => {
          const aValue = a[field];
          const bValue = b[field];
          if(sortingColumn.type === 'number'){
          return sortingColumn.ascending ? aValue - bValue : bValue - aValue;
        }else{
          return sortingColumn.ascending
            ? String(aValue).localeCompare(String(bValue))
            : String(bValue).localeCompare(String(aValue));
        }
        });
        setUtentiLista(sortedList);
      }
    };

    return (
        <thead>
 <tr style={{...styleTr}}>

        {staffColumns.map((column) =>  {
            return(
             <th key={column.field} onClick={() =>handleSort(column.field)} style={column.style}>
             {column.name}
            </th>  
            )
        })
    }
     </tr>
    </thead>
    )
}
export default ColoneStaff;

现在我的问题非常简单,我如何检查我的

utentiLista.keys
是否等于我的 StaffColumns 列表。在 StaffColumns 内部,我创建了一个没有 usersList 对象属性的对象,因此不会打印表数据中的任何内容,而只是打印空列。这是
{name:'Action'}
对象。 我希望能够在我的columnStaff列表中找到“入侵者”对象,而不是删除它,而是每次添加像“Action”这样的列并且它不对应于usersList对象的任何值时,并且它然后去打印一个简单的“在该列的数据Action”。
<td>Missing Value</td>
这是我的 usersList 数组:

  const [utentiLista, setUtentiLista] = useState([
    {id: 1, username: 'FEDERICOSCHI', data: '...', amount: 2000, status: 'Completed'},
    {id: 2, username: 'Feryzz', data: '...', amount: 15, status: 'Completed'},
    {id: 3, username: 'Cinquanta', data: '...', amount: 27, status: 'Pending'},
    {id: 4, username: 'NotAffected', data: '...', amount: 50, status: 'In progress'},
    {id: 5, username: 'Ytnoos', data: '...', amount: 12, status: 'Completed'},
    {id: 6, username: 'Mattia882', data: '...', amount: 33, status: 'In progress'}
  ]);
javascript reactjs sorting html-table jsx
1个回答
0
投票

为了确保您的 utentiLista(用户列表)与 StaffColumns 组件中定义的列保持一致,您可以在 StaffData 组件中添加检查。这个想法是迭代列并根据每个用户对象中是否存在相应的属性来动态创建表 data() 元素。

这里有一个快速的方法:

将 StaffColumns 传递到 StaffDati:首先,您需要将列状态 (staffColumns) 从 ColoneStaff 传递到 StaffDati 作为 prop。这将为 StaffDati 提供所需的有关应显示哪些列的信息。

基于列创建元素:在 StaffDati 中,迭代 StaffColumns 以创建元素。对于每一列,检查用户对象中是否存在相应的属性。如果存在,则显示该值;如果没有,则显示一个占位符,例如“缺失值”。

const StaffDati = ({ utentiLista, staffColumns }) => {
    // ... existing code ...

    return (
        <tbody style={{ width: '100%' }}>
            {utentiLista.map((utente) => (
                <tr key={utente.id} style={{ width: '100%' }}>
                    {staffColumns.map((column) => {
                        // Check if the user object has the property corresponding to the column
                        if (utente.hasOwnProperty(column.field)) {
                            return <td style={styleText}>{utente[column.field]}</td>;
                        } else {
                            // If the property doesn't exist, display a placeholder
                            return <td style={styleText}>Missing Value</td>;
                        }
                    })}
                </tr>
            ))}
        </tbody>
    );
};

export default StaffDati;

此方法将动态地将您的用户数据与列对齐。如果您添加的新列在用户对象中没有相应的属性,它将自动在该列的单元格中显示“缺失值”(或您选择的任何占位符)。

希望这对您有帮助!如果您还有其他问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.