我使用React Virtualized Table。数据来自Redux,并在单击“提交”按钮后从输入中添加。表也已排序,但问题是行不会自动添加。仅在单击某些标题时才调用this._sort函数。此功能负责更新状态(将对象添加到列表)。我希望在不排序的情况下自动添加行。正确的做法是什么?
import React, { Component } from "react";
import { Column, Table, AutoSizer, SortDirection } from "react-virtualized";
import { connect } from "react-redux";
import styled from "styled-components";
import "react-virtualized/styles.css";
import _ from "lodash";
class RightSide extends Component {
constructor(props) {
super(props);
const sortBy = "name";
const sortDirection = SortDirection.ASC;
const expensesArray = this.props.expenses;
this.state = {
sortBy,
sortDirection,
expensesArray
};
}
render() {
const { expensesArray, sortBy, sortDirection } = this.state;
return (
<StyledContainer>
<AutoSizer disableWidth>
{({ height }) => (
<TableWrapper>
<Table
rowCount={expensesArray.length}
width={500}
height={height}
rowHeight={60}
rowGetter={({ index }) => expensesArray[index]}
headerHeight={50}
// Rows are only renderer when clicked on header
sort={this._sort}
sortBy={sortBy}
sortDirection={sortDirection}
>
<Column label="Name" dataKey="name" width={125} />
<Column label="Cost" dataKey="cost" width={125} />
<Column label="Date" dataKey="date" width={125} />
<Column label="Group" dataKey="group" width={125} />
</Table>
</TableWrapper>
)}
</AutoSizer>
</StyledContainer>
);
}
_sortList = ({ sortBy, sortDirection }) => {
let newList = _.sortBy(this.props.expenses, [sortBy]);
if (sortDirection === SortDirection.DESC) {
newList.reverse();
}
return newList;
};
_sort = ({ sortBy, sortDirection }) => {
const sortedList = this._sortList({ sortBy, sortDirection });
this.setState({ sortBy, sortDirection, sortedList });
};
}
const mapStateToProps = state => {
return { expenses: state.expenses };
};
export default connect(
mapStateToProps,
null
)(RightSide);
// ________________________________________________________ STYLED COMPONENTS ____________________________________________________
const StyledContainer = styled.div`
height: 638px;
width: 519px;
flex: 1;
`;
const TableWrapper = styled.div`
.ReactVirtualized__Table {
border: none;
user-select: none;
}
.ReactVirtualized__Table__headerColumn {
text-align: center;
outline: 0;
}
.ReactVirtualized__Table__headerRow {
background: #414a56;
color: white;
font-family: "Roboto-Condensed", sans-serif;
}
.ReactVirtualized__Table__row {
background: papayawhip;
color: #414a56;
font-family: "Roboto-Condensed", sans-serif;
}
.ReactVirtualized__Table__rowColumn {
text-align: center;
}
.ReactVirtualized__Table__sortableHeaderColumn {
}
.ReactVirtualized__Table__sortableHeaderIcon {
}
`;