[英]Sort array of objects with Lodash sortBy instead of custom sort function
[英]What is the error in sortBy function
我是新來的反應者,在從json對象重做的反應中排序數據表時遇到問題。 我已經正確呈現了數據表,但是當我嘗試使用單元格組件上的onClick對數據表進行排序時,錯誤顯示為“ ./src/App.js第34行:'tableData'未定義為no-undef”。
請指出我正在犯什么錯誤。源代碼是:
import React from 'react';
import axios from 'axios';
import {Table, Column, Cell} from 'fixed-data-table-2';
import 'fixed-data-table-2/dist/fixed-data-table.css';
class App extends React.Component {
constructor (props) {
super(props);
this.state = { tableData : []};
this.sortBy = this.sortBy.bind(this);
}
sortBy(sort_attr) {
this.setState({
tableData: tableData.sort('ascending')
});
}
componentDidMount() {
axios.get('https://drupal8.sample.com/my-api/get.json', {
responseType: 'json'
}).then(response => {
this.setState({ tableData: response.data });
console.log(this.state.tableData);
});
}
render() {
const rows = this.state.tableData;
return (
<Table
rowHeight={50}
rowsCount={rows.length}
width={500}
height={500}
headerHeight={50}>
<Column
header={<Cell onClick= {this.sortBy}>resourceID</Cell>}
columnKey="resourceID"
cell={({ rowIndex, columnKey, ...props }) =>
<Cell {...props}>
{rows[rowIndex][columnKey]}
</Cell>}
width={200}
/>
<Column
header={<Cell>resourceType</Cell>}
columnKey="resourceType"
cell={({ rowIndex, columnKey, ...props }) =>
<Cell {...props}>
{rows[rowIndex][columnKey]}
</Cell>}
width={200}
/>
<Column
header={<Cell>tenantName</Cell>}
columnKey="tenantName"
cell={({ rowIndex, columnKey, ...props }) =>
<Cell {...props}>
{rows[rowIndex][columnKey]}
</Cell>}
width={200}
/>
</Table>
);
}
}
export default App;
在您的sortBy
函數中,您正在使用tableData
而不將其從狀態中破壞
sortBy(sort_attr) {
const {tableData} = this.state;
this.setState({
tableData: tableData.sort('ascending')
});
}
但是,由於要基於prevState
更新currentState
,因此應使用functional setState
例如
sortBy(sort_attr) {
this.setState(prevState => ({
tableData: prevState.tableData.sort('ascending')
}));
}
檢查此問題以獲取有關when to use functional setState
更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.