如何在第三次点击时返回我的原始列表



前端代码

const [customerList, setCustomerList] = useState([]); //store all that information of the database in a list
//make an axios request to get information from database
useEffect(() => {
Axios.get("http://localhost:3001/customers").then((response) => {
setCustomerList(response.data);
});
}, []);
//sort function final
const [counter, setCounter] = useState(0);
const [sortedCustomerList, setSortedCustomerList] = useState([]);
function sortCustomer() {
const sortedCustomer = [...customerList];
let sortCount = counter;
//check the current sortCount, if it is 3 then go back to 1, if not then increase by 1
if (sortCount === 3) {
sortCount = 1;
setCounter(1);
} else {
sortCount += 1;
setCounter(sortCount);
}
console.log(sortCount);
if (sortCount < 3) {
sortedCustomer.sort(function (x, y) {
if (sortCount === 1) {
return x.contacted === y.contacted
? 0
: x.contacted === "Yes"
? -1
: 1;
} else if (sortCount === 2) {
return x.contacted === y.contacted
? 0
: x.contacted === "Yes"
? 1
: -1;
}
});
setCustomerList(sortedCustomer);
} else {
setCustomerList(customerList);
}
}
<th onClick={() => sortCustomer()}>Contacted?</th>

我已经实现了一个排序函数onClick方法。因此,第一次单击返回降序列表,第二次单击返回升序列表,但第三次单击不会返回原始customerList。如何解决这个问题。

const [customerList, setCustomerList] = useState([]); //store all that information of the database in a list
const [counter, setCounter] = useState(0);
const [sortedCustomerList, setSortedCustomerList] = useState([]);
useEffect(() => {
Axios.get("http://localhost:3001/customers").then((response) => {
setCustomerList(response.data);
setSortedCustomerList(response.data);
});
}, []);
function sortCustomer() {
const sortedCustomer = [...customerList];
let sortCount = counter;
if (sortCount === 3) {
sortCount = 1;
setCounter(1);
} else {
sortCount += 1;
setCounter(sortCount);
}
if (sortCount < 3) {
sortedCustomer.sort(function (x, y) {
if (sortCount === 1) {
return x.contacted === y.contacted
? 0
: x.contacted === "Yes"
? -1
: 1;
} else if (sortCount === 2) {
return x.contacted === y.contacted
? 0
: x.contacted === "Yes"
? 1
: -1;
}
});
setSortedCustomerList(sortedCustomer);
} else {
setSortedCustomerList(customerList);
}
}
Use sortedCustomerList to print on the screen
<th onClick={() => sortCustomer()}>Contacted?</th>

最新更新