I have designed a table which will read a object array and a dropdown list for ordering control.
However, when I select other ordering value in dropdown list. The front end table did not update at the same time. It will have a delay, please see the following example.
T0: default select order by "name" -> front end correct(Order by "name")
T1: select order by "age" -> front-end no update (still order by "name")
T2: select order by "name" -> front-end update (order by "age")
T3: select order by "age" -> front-end update (order by "name")
My object array
var data = [
{
key: 1,
name: 'AAA',
age: '10',
},
{
key: 2,
name: 'BBB',
age: '8',
},
{
key: 3,
name: 'name',
age: '12',
},
]
const [listData, setListData] = useState(data);
Drop down control
const handleOrderChange = (value) => {
setOrderValue(value);
};
useEffect(() => {
console.log(orderValue.value); //match what I click
switch (orderValue.value) {
case 'name':
listData.sort((a, b) => (a.name > b.name ? 1 : -1));
break;
case 'age':
listData.sort((a, b) => (a.age> b.age? 1 : -1));
break;
default:
console.log('Default');
}
console.log(listData); //match what I expected
}, [orderValue]);
Front-End
{/* Data */}
{listData.map((item) => (
<DataDetail
key={item.key}
name={item.name}
age={item.age}
></DataDetail>
))}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…