【发布时间】:2021-08-23 20:47:48
【问题描述】:
我在custom table 中添加了sort。如果我在console 中看到它,排序正在工作,它表明数据正在更新。
但是我的TableBody 一次后没有更新。
不知道发生了什么。
TableWrapper.js
const TableWrapper = ({...props}) => {
const { tableData, columns } = props;
const [ visibleData, setVisibleData ] = useState([])
const sortColumn = (dataIndex, sortOrder) => {
let sortedData = tableData.data.firstResponse.sort(function(a, b){
if(a.dataIndex < b.dataIndex) return -1; // Ascending Order
if(a.dataIndex > b.dataIndex) return 1; // Descending Order
return 0; // Default
})
if (sortOrder === 'desc') {
sortedData.reverse();
}
console.log(dataIndex, sortOrder)
console.log(sortedData)
setVisibleData(sortedData);
}
return (
<>
<table>
<TableHead headers={columns} isCheckBox={true} isSelectAll={selectAll} selectAllChecked={selectAllChecked} sortColumn={sortColumn} />
<TableBody rows={tableData} tableData={visibleData} headers={columns} isCheckBox={true} isSelectAll={selectAll} isCheckBoxChecked={selectedCheckBox} />
</table>
</>
);
};
export default TableWrapper;
TableHead.js
const TableHead = ({...props}) => {
const { headers, isCheckBox, isSelectAll, selectAllChecked, sortColumn } = props;
const [sortorState, setSortorState] = useState("desc");
const checkRef = useRef();
const getSortorState = sortorState => {
switch (sortorState) {
case "asc":
return "desc";
case "desc":
return "asc";
default:
return "desc";
}
};
const handleSorterChange = (dataIndex, sortOrder) => {
const updatedSortorState = getSortorState(sortOrder);
setSortorState(updatedSortorState);
sortColumn(dataIndex, updatedSortorState)
};
return (
<thead>
<tr>
{
isCheckBox &&
<th key={`table-header-checkBox`}><input id="select-all-checkBox" type="checkbox" onClick={selectAllChecked} ref={checkRef} /></th>
}
{headers.map(item => {
const { key, field, style, header, sortable} = item
return (
<>
{sortable ?
<th
className={"table-header" + " sortable"}
onClick={() =>
handleSorterChange(field, sortorState)
}
>
<span>{header}</span>
</th>
:
<th
key={`table-header-${key}`}
style={style}>
{header}
</th>
}
</>
)})}
</tr>
</thead>
);
};
export default TableHead;
我需要一些帮助,为什么它没有得到更新。
Or is there any better way to achieve the sorting?
在图片中,我正在尝试对first name 进行排序,如果您看到控制台数据正在排序,但有一次之后table data 没有得到更新
【问题讨论】:
标签: javascript jquery reactjs react-redux react-hooks