我刚接触react,在react中对json对象中的数据表进行排序时遇到了问题。我已经正确地呈现了数据表,但是当我尝试在单元组件上使用onClick对数据表进行排序时,错误显示“./src/App.jsLine 34:'tableData‘is not defined no-undef”。
请指出I am making.The源代码的错误是什么:
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;发布于 2018-03-20 17:31:59
在您的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的更多信息,请查看此问题
https://stackoverflow.com/questions/49380319
复制相似问题