首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React表排序不一致,它一直更改回默认状态

React表排序不一致,它一直更改回默认状态
EN

Stack Overflow用户
提问于 2019-09-09 05:37:33
回答 1查看 1.9K关注 0票数 2

我正在对react表进行排序,当用户单击表标题时,需要对表进行排序,排序是有效的,但问题是我每秒都会通过SignalR集线器接收新数据,并且它会将状态udata设置为新数据。当用户单击表标题时,它对表进行排序,但再次返回到由新数据更改的新状态。并将已排序的表取消为未排序。

有没有办法让我在保持排序状态的同时还能接收数据?

代码语言:javascript
复制
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>
    );
}
EN

回答 1

Stack Overflow用户

发布于 2019-09-09 11:20:56

明天我也许能帮上更多忙。我现在用的是一台坏了一半的笔记本。

这是一个基本的想法,我的语法可能有点离谱。

代码语言:javascript
复制
//might need better default values for sortEvent and sortKey
this.state = {
    udata: [],
    sortEvent: {},
    sortKey: ''
}

connection.on("APIDataChannel", function (data) {
  this.setState({ udata: data });
  // I'm not sure about sortEvent in this context
  onSort(this.state.sortEvent, this.state.sortKey);
  //may need to be a callback like:
  this.setState({ udata: data },onSort(this.state.sortEvent, this.state.sortKey));
   // console.log(data);
}.bind(this));

onSort(event, sortKey, data) {
    this.setState({
      sortEvent: event,
      sortKey: sortKey 
     });
    const data = this.state.udata;
    data.sort((a, b) => a[sortKey].localeCompare(b[sortKey]))
    // I'm not sure what this is doing:
    this.setState({ data })
}

<th onClick={e => this.onSort(e, 'appName', this.state.udata)}>App Name</th>

如果你每次都调用它,我也只会在setState中使用它。也许也可以传递数据。所以:

代码语言:javascript
复制
//might need better default values for sortEvent and sortKey
this.state = {
    udata: [],
    sortEvent: {},
    sortKey: ''
}

connection.on("APIDataChannel", function (data) {
  // one onSort call
  onSort(this.state.sortEvent, this.state.sortKey, data);
   // console.log(data);
}.bind(this));

onSort(event, sortKey, data) {
    data.sort((a, b) => a[sortKey].localeCompare(b[sortKey]))
    // Set the state of everything once:
    this.setState({
      sortEvent: event,
      sortKey: sortKey,
      udata: data 
     });
}
<th onClick={e => this.onSort(e, 'appName', this.state.udata)}>App Name</th>

我总是三思而后行。我真的不会将数据保存到状态。Id do:

代码语言:javascript
复制
//might need better default values for sortEvent and sortKey
this.state = {
    sortEvent: {},
    sortKey: ''
},
this.data = [];

connection.on("APIDataChannel", function (data) {
  this.data = data;
  // one onSort call
  onSort(this.state.sortEvent, this.state.sortKey);
   // console.log(data);
}.bind(this));

onSort(event, sortKey) {
    this.data.sort((a, b) => a[sortKey].localeCompare(b[sortKey]))
    // Set the state of everything once:
    this.setState({
      sortEvent: event,
      sortKey: sortKey,
      //if you really need to set data to state you could do it here
      udata: data 
     });
}
<th onClick={e => this.onSort(e, 'appName')}>App Name</th>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57845933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档