我试图避免使用反应状态以获得更好的性能。但是,我不知道如何对表数据进行排序。我试图在需要使用type(“ asc”或“ desc”)并根据名称或标题等进行排序的列中使用sort函数。这是我的表的配置和代码
代码
const sortBy = (data, key, type = "asc") => data.sort((a, b) => a[key].toLowerCase() < b[key].toLowerCase());
const columns = {
name: {
key: "name",
label: "Listing Name",
css: "color: #444; font-size: 1.1rem; font-weight: bold;",
content: (item: Object) => (
<NameColumn>
{item.url && <Avatar name={item.name} url={item.url} size={80} type="square" />}
<NameWrapper>
<Name>{item.name}</Name>
{item.location && <SubName color='#797979'>{item.location}</SubName>}
</NameWrapper>
</NameColumn>
)
},
agent: {
key: "agent",
label: "Agent",
sort: (data: Array<Object>, item: Object) => sortBy(data, item, 'desc'),
isSortable: true,
hideOnPhone: true
},
price: {
key: "price",
label: "Prices",
hideOnPhone: true
},
};
const userData = [
{
id: 1,
name: "Rahul",
location: 'Delhi',
agent: "hello man",
price: '$15000',
},
{
id: 2,
name: "Sachin Tendulkar",
location: 'Delhi',
agent: "Mumbai Inc",
price: '$15000',
},
];
const rowConfig = {
uniqueKey: "id",
css: `
height: 100px;
&:hover {
background-color: rgba(216, 216, 216, 0.2)};
}
`,
onClick: (e, item) => {
console.log("row was clicked", item);
}
};
type Props = {
location: Object
};
const Tables = ({ location }: Props) => {
const queries = new URLSearchParams(location.search);
return (
<Main>
<Table
rowConfig={rowConfig}
columns={columns}
data={userData}
totalPages={10}
currentPage={
queries.has("page") ? parseInt(queries.get("page"), 10) : 1
}
basePageLink={""}
/>
</Main>
);
};
export default Tables;
const Table = ({
columns,
data = [],
rowConfig: { uniqueKey = "id", css , onClick } = {},
currentPage,
totalPages,
basePageLink
}: Props) => {
const headerColumns = () =>
Object.keys(columns).map(key => (
<Th
key={key}
align={columns[key].align}
width={columns[key].width}
onClick={() => columns[key].isSortable && columns[key].sort(data, key)}
css={columns[key].cssHeader}
>
{columns[key].label ? columns[key].label : ""}
</Th>
));
const cell = (key, item) => (
<Td
key={key}
align={columns[key].align}
width={columns[key].width}
css={columns[key].css}
>
{columns[key].content ? columns[key].content(item) : item[key]}
</Td>
);
const row = (item: Object) => (
<Tr
key={item[uniqueKey]}
css={css}
onClick={onClick ? (e: Event) => onClick(e, item) : null}
>
{Object.keys(columns).map(key => cell(key, item))}
</Tr>
);
return (
<Main>
<T>
<thead>
<tr>{headerColumns()}</tr>
</thead>
<tbody>{data.map(i => row(i))}</tbody>
</T>
<TablePagination
currentPage={currentPage}
totalPages={totalPages}
basePageLink={basePageLink}
/>
</Main>
);
};
export default Table;
我正在做的方式无法正常工作,因为我没有使用react状态,该状态将通知react状态已更改,因此请重新渲染agent列(目前仅在agent列中使用排序)。
有任何建议吗?帮助将不胜感激!