我正在做一个React项目。在该项目中,我在一个表格中显示数据,这些数据来自后台。在该表中,我显示了来自后台的最小值和最大值。
在表中我有两个按钮,第一个按钮是 "Change to Min",第二个按钮是 "Change to Max"。
现在我想做的是,我想对最大值进行排序。我的目标是,如果我点击 "更改为最小值 "按钮,那么在用户界面中,所有的最大值将按照升序到降序显示。现在,如果我点击 "更改为最大 "按钮,那么在用户界面中,所有的最大值必须以升序到降序的方式显示。
我也写了排序函数,并将该函数应用于 "改成最小值 "按钮。但我不知道如何将该函数传递到另一个状态。
这是list.js
import React, { useState, useEffect } from 'react';
import { Table, Button } from 'reactstrap';
import Aumservice from '../../service/aum-service';
import { MdEdit } from 'react-icons/md';
import { IconContext } from "react-icons";
const List = (props) => {
const [sortData, setSortData] = useState(null)
const [data, setData] = useState([])
useEffect(() => {
(async function () {
const response = await Aumservice.getAum()
const dataResponse = response.data.list.map(ele => ele.maxValue)
setSortData(dataResponse)
setData(response.data.list)
})()
}, [])
const sortAscending = () => {
let sortedData = sortData.sort((a, b) => a - b)
console.log(sortedData)
setData(sortedData)
}
const sortDescending = () => {
let sortedData = sortData.sort((a, b) => b - a)
setData(sortedData)
}
return (
<div>
<IconContext.Provider
value={{ size: '25px' }}
>
<Table bordered>
<thead>
<tr>
<th>So No</th>
<th>Min</th>
<th>Max</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{data.map((currentValue, index) => {
return < tr key={index + 1} >
<th scope="row">{index + 1}</th>
<td>{currentValue.minValue}</td>
<td>{currentValue.maxValue}</td>
</tr>
})}
</tbody>
</Table>
</IconContext.Provider>
<div className='min pr-5'>
<Button onClick={sortAscending} className='primary'>Change to Min</Button>
</div>
<div className='max'>
<Button className='secondary'>Change to Max</Button>
</div>
</div >
)
}
export default List
你好,我已经更新了代码。希望它能帮助你。
import React, {useState, useEffect} from 'react';
import {Table, Button} from 'reactstrap';
import {IconContext} from "react-icons";
const SortedDataExample = (props) => {
const [sortData, setSortData] = useState([]);
useEffect(() => {
setSortData([23, 435, 23, 345, 76, 878]);
}, []);
const sortAscending = () => {
let sortedData = sortData.sort((a, b) => a - b);
console.log(sortedData);
setSortData(sortedData);
};
const sortDescending = () => {
let sortedData = sortData.sort((a, b) => b - a);
console.log(sortedData);
setSortData(sortedData);
};
return (
<div>
<IconContext.Provider
value={{size: '25px'}}
>
<Table bordered>
<thead>
<tr>
<th>So No</th>
<th>Min</th>
<th>Max</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{sortData.map((currentValue, index) => {
return < tr key={index + 1}>
<th scope="row">{index + 1}</th>
<td>{currentValue.minValue}</td>
<td>{currentValue.maxValue}</td>
</tr>
})}
</tbody>
</Table>
</IconContext.Provider>
<div className='min pr-5'>
<Button onClick={sortAscending} className='primary'>Change to Min</Button>
</div>
<div className='max'>
<Button onClick={sortDescending} className='secondary'>Change to Max</Button>
</div>
</div>
)
};
export default SortedDataExample