如何使用React中的功能组件将状态传递给同一组件中的另一个状态

时间:2020-04-22 10:39:23

标签: reactjs

我正在研究一个React项目,在这个项目中我试图进行排序。在我的组件中,我有

两个按钮。第一个按钮是“更改为最小值”,第二个按钮是“更改为最大值”。

在同一组件中,我将显示来自后端的数据。

现在,如果我单击按钮,则排序逻辑状态必须应用于我所显示的数据

使用地图方法。

这是list.js

authorization-code

如果我不确定是否有疑问,请发表评论。

1 个答案:

答案 0 :(得分:1)

如果我做对了,您希望通过maxValue对数据进行排序,其方式取决于单击哪个按钮(升/降)。

  1. 映射元素中有一个错字,而不是setData.map((..,您需要data.map((..
  2. 必须使用onClick功能在第二个按钮上添加sortDescending事件。
  3. 您不需要第二个变量sortData来对数据进行排序,您可以对从响应中获得的现有列表进行排序。

根据以上结论,我已经编辑了您的代码:

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 [data, setData] = useState([])

    useEffect(() => {
        (async function () {
            const response = await Aumservice.getAum()
            setData(response.data.list)
        })()
    }, [])

    const sortAscending = () => {
      let copyData = JSON.parse(JSON.stringify(data));
      // If you want to sort by minValue,just change accordingly the below properties
      let sortedData = copyData.sort((a, b) => (a.maxValue > b.maxValue) ? 1 : -1);
      console.log(sortedData)
      setData(sortedData)
    }
    
    const sortDescending = () => {
      let copyData = JSON.parse(JSON.stringify(data));
      // If you want to sort by minValue,just change accordingly the below properties
      let sortedData = copyData.sort((a, b) => (a.maxValue < b.maxValue) ? 1 : -1);
      console.log(sortedData)
      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 onClick={sortDescending} className='secondary'>Change to Max</Button>
            </div>
        </div >
    )
}

export default List