我从aws dynamo数据库动态渲染表。我希望首先呈现最新的帖子。我使用createdAt变量作为键,但表仍然随机呈现。我无法弄清楚什么是错误的,并希望得到帮助。代码:
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
sort: {
column: null,
direction: 'desc',
}
};
this.onSort = this.onSort.bind(this);
}
async componentDidMount() {
if (!this.props.isAuthenticated) {
return;
}
try {
const results = await this.notes();
this.setState({ notes: results });
} catch (e) {
alert(e);
}
this.setState({ isLoading: false });
}
notes() {
return invokeApig({ path: "/notez" });
}
handleNoteClick = event => {
event.preventDefault();
this.props.history.push(event.currentTarget.getAttribute("href"));
}
onSort(column) {
return(function(e) {
let direction = this.state.sort.direction;
if (this.state.sort.column === column){
direction = this.state.sort.direction === 'asc' ? 'desc' : 'asc';
}
const sortedData = this.state.notes.sort((a, b) => {
if(column === 'date') {
return a.createdAt - b.createdAt;
}
});
if(direction === 'desc'){
sortedData.reverse();
}
this.setState({
notes: sortedData,
sort: {
column,
direction,
}
});
}).bind(this);
}
renderNotesList(notes) {
var styles = {
progress: {
backgroundColor: "#ffff00",
color: '#000000'
},
completed: {
backgroundColor: "#66CD00",
color: '#000000'
}
}
return (
<div>
<Table responsive hover>
<thead>
<tr>
<th>Title</th>
<th>Employee</th>
<th className="sortable" onClick={this.onSort('date')}>
Created
</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.state.notes.map((note) =>
<tr
key={note.createdAt}
href={`/notes/${note.noteId}`}
onClick={this.handleNoteClick}
className="workOrders"
>
<td>{note.title}</td>
<td>{note.employee}</td>
<td>{new Date(note.createdAt).toLocaleString()}</td>
{note.jobStatus === 'In Progress' || note.jobStatus !== 'Completed' ? <td style={styles.progress}>{note.jobStatus}</td> : <td style={styles.completed}>{note.jobStatus}</td>}
</tr>
)}
</tbody>
</Table>
</div>
);
}
createdAt在数据库中存储为整数值:
我认为我能够将列表从最新到最旧呈现,因为最近创建的日期值更高。这可能吗?
答案 0 :(得分:0)
您没有在初始渲染上对数据进行排序。您只能在表标题列&#34;创建&#34;之后对它们进行排序。点击。您可以尝试在this.onSort('date')
函数中的this.setState({ notes: results });
之后添加componentDidMount
,或者更好,只需在将results
传递到状态之前对其进行排序:
const results = await this.notes();
const notes = results.sort((a, b) => {
return a.createdAt - b.createdAt;
});
this.setState({ notes });
当然,您不想忘记将构造函数中的默认排序列从null
更改为'date'
。