【发布时间】:2019-09-09 12:01:23
【问题描述】:
当用户单击表头时,我正在处理此反应表排序,它需要对表进行排序,排序正常,但问题是我每秒通过 SignalR 集线器接收新数据,它设置状态 @987654321 @ 到新数据。当用户单击表头时,它会对表进行排序,但又会返回到由新数据更改的新状态。并将已排序的表取消为未排序的。
有什么方法可以保持排序状态并仍然接收数据?
constructor() {
super()
this.state = {
udata: []
}
this.onSort = this.onSort.bind(this)
let connection = new signalR.HubConnectionBuilder()
.withUrl("/signalserver")
.build();
connection.start().then(function () {
}).catch(function (err) {
return console.error(err.toString());
});
connection.on("APIDataChannel", function (data) {
this.setState({ udata: data });
// console.log(data);
}.bind(this));
async function start() {
try {
await connection.start();
console.log("connected");
} catch (err) {
console.log(err);
setTimeout(() => start(), 5000);
}
};
connection.onclose(async () => {
await start();
});
}
renderItem(item, key) {
const itemRows = [
<tr onClick={clickCallback} key={"row-data-" + key}>
<td>{item.appName}</td>
<td>
<h6 className="text-muted"><i className={"fa fa-circle text-c-" + (item.appState === 'STARTED' ? 'green' : 'red') + " f-10 m-r-15"} />{item.appState}</h6>
</td>
<td>{item.spaceName}</td>
<td>
<h6 className="text-muted">{item.orgName}</h6>
</td>
<td>
<h6 className="text-muted">{new Date(item.appUpdatedAt).toLocaleString()}</h6>
</td>
</tr>
];
return itemRows;
}
onSort(event, sortKey) {
const data = this.state.udata;
data.sort((a, b) => a[sortKey].localeCompare(b[sortKey]))
this.setState({ data })
}
render() {
let allItemRows = [];
this.state.udata.forEach((item, key) => {
const perItemRows = this.renderItem(item, key);
allItemRows = allItemRows.concat(perItemRows);
});
return (
<Aux>
<Row>
<Table hover responsive>
<thead>
<tr>
<th onClick={e => this.onSort(e, 'appName')}>App Name</th>
<th>State</th>
<th>Space</th>
<th>Organization</th>
<th onClick={e => this.onSort(e, 'appUpdatedAt')}>Updated At</th>
</tr>
</thead>
<tbody>
{allItemRows}
</tbody>
</Table>
</Row>
</Aux>
);
}
【问题讨论】:
-
需要在状态下保存udata吗?我通常将数据存储在它之外。
-
现在不是真的需要我在状态中保存数据,但在未来,我打算使用全局状态,因为我有类似的 4 个不同环境的页面。在一个地方提取数据然后在整个应用程序中使用它更有意义。
-
我认为您可以将表格排序设置保存为 state。也许在将它保存到状态之前使用这些设置对 udata 进行排序。
-
你能告诉我怎么做吗?
标签: javascript reactjs datatables signalr signalr.client