第一部分包括将表的
items
传递给 useSortableData
函数,以及确定排序顺序的 config
变量。
const useSortableData = (items, config = null) => {
const [sortConfig, setSortConfig] = React.useState(config);
const sortedItems = React.useMemo(() => {
let sortableItems = [items];
console.log(sortableItems);
if (sortConfig !== null) {
sortableItems.sort((a, b) => {
if (a[sortConfig.key] < b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? -1 : 1;
}
if (a[sortConfig.key] > b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? 1 : -1;
}
return 0;
});
}
return sortableItems;
}, [items, sortConfig]);
const requestSort = (key) => {
let direction = 'ascending';
if (
sortConfig &&
sortConfig.key === key &&
sortConfig.direction === 'ascending'
) {
direction = 'descending';
}
setSortConfig({ key, direction });
};
return { items: sortedItems, requestSort, sortConfig };
};
第二部分
const ProductTable = (products) => {
const { items, requestSort, sortConfig } = useSortableData(products);
console.log(items);
const getClassNamesFor = (name) => {
if (!sortConfig) {
return;
}
return sortConfig.key === name ? sortConfig.direction : undefined;
};
return (
<table>
<thead>
<tr>
<th scope="col" class="py-4">
<button
type="button"
onClick={() => requestSort('symbol')}
className={getClassNamesFor('symbol')}
>
Symbol
</button>
</th>
<th scope="col" class="py-4">
<button
type="button"
onClick={() => requestSort('beta')}
className={getClassNamesFor('beta')}
>
Beta
</button>
</th>
<th scope="col" class="py-4">
<button
type="button"
onClick={() => requestSort('volAvg')}
className={getClassNamesFor('volAvg')}
>
Average Volume
</button>
</th>
<th scope="col" class="py-4">
<button
type="button"
onClick={() => requestSort('mktCap')}
className={getClassNamesFor('mktCap')}
>
Market Cap
</button>
</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.symbol}>
<td>{item.beta}</td>
<td>{item.volAvg}</td>
<td>{item.mktCap}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
最后,
<ProductTable products={
store.stocks.map((stock) => {
return {
symbol: stock.symbol,
beta: stock.beta,
mktCap: stock.mktCap,
volAvg: stock.volAvg,
};
})} />
未产生预期输出,且未显示表格。我确实在浏览器的控制台上打印了
console.log(sortableItems);
行,它显示数组的长度是 1
而不是 65
使用 扩展语法 将
sortableItems
声明为 items
的副本。
// Currently, you declare sortableItems as a two dimensional array.
let sortableItems = [items];
// Instead, you should declare a one-dimensional array by spreading items
let sortableItems = [...items];