react-redux實現升序降序排序
阿新 • • 發佈:2018-11-29
- action.js
下面程式碼中的patientList是一個數據陣列,比較patientList陣列中的sirenId,然後patientList這一行資料也排序
export function upSort(patientList) { return async dispatch => { var sortarr = [] for (var i = 0; i < patientList.length; i++) { for (var j = 0; j < patientList.length - i - 1; j++) { if (patientList[j + 1].sirenId > patientList[j].sirenId) { var temp; temp = patientList[j]; patientList[j] = patientList[j+1]; patientList[j+1] = temp; } } sortarr.push(temp) } console.log('sortarr asc: ',sortarr); // dispatch(changeSort(sortarr)); }; } export function downSort(patientList) { return async dispatch => { var sortarr2 = [] for (var i = 0; i < patientList.length; i++) { for (var j = 0; j < patientList.length - i - 1; j++) { if (patientList[j + 1].sirenId < patientList[j].sirenId) { var temp; temp = patientList[j]; patientList[j] = patientList[j+1]; patientList[j+1] = temp; } } sortarr2.push(temp) } console.log('sortarr2 desc: ',sortarr2); // dispatch(changeSort(sortarr2)); }; } function changeSort(patientsList) { return { type: TYPES.PATIENTS_LIST, text: patientsList }; }
- 只摘取部分重要程式碼
import React, { Component } from "react"; import { connect } from 'react-redux' import { Table, Menu, Icon, Popup, Button, Header, Input, Pagination } from "semantic-ui-react"; import "semantic-ui-css/semantic.min.css"; import "./DeviceList.css"; import _ from 'lodash' import { getPatientsList, getPatientInfo, upSort, downSort } from "../action/Action"; import up from './up.png' import down from './down.png' class DeviceList extends Component { constructor(props) { super(props); this.state = { //先順序排序 up_down: true }; } rank() { const { upSort } = this.props; const { downSort } = this.props; const up_down = !this.state.up_down; this.setState({ up_down }); this.state.up_down ? (upSort(this.props.listPatients)) : (downSort(this.props.listPatients)); } render() { let self = this; return ( <div className="device-list-container"> <Table celled className="result-table"> <Table.Header> <Table.Row> <Table.HeaderCell className="totalbox">SirenID <div className="updownbox" onClick={this.rank.bind(this)}> <img src={up} className='upbox' /> <img src={down} /> </div> </Table.HeaderCell> </Table.Row> </Table.Header> </Table> </div> ); } } const mapDispatchToProp = dispatch => ({ getPatientsList: self => dispatch(getPatientsList(self)), getPatientInfo: (self, patientList) => dispatch(getPatientInfo(self, patientList)), upSort: patientList => dispatch(upSort(patientList)), downSort: patientList => dispatch(downSort(patientList)) });