如何使BootstrapTable重新绘制更新的数据?

问题描述

我有一个来自react-bootstrap的表格,其中显示了具有几列的设备列表。我想更改此设置,以便您可以按列重新排序,因此我从react-bootstrap-table-next切换到BootstrapTable。但是我的问题是,更改组件的状态不会导致表更新-仅在单击列以重新排序表时才会发生。

编写代码以创建devices_table并将其保存到状态,然后调用API获取设备版本并将其添加到状态中,从而导致组件重绘。但是,再次调用render()时,不会将其他数据添加到表中。

我在https://codesandbox.io/s/react-bootstrap-table-next-new-data-problem-5w0op

创建了一个工作示例
import React,{ Component } from 'react'
import BootstrapTable from 'react-bootstrap-table-next'

class DeviceTable extends Component {

    constructor(props) {
        super(props)

        this.state = {
            devices_table: {}
        }
    }

    componentDidUpdate(prevProps) {
        if (prevProps.devices !== this.props.devices) {
            let devices_table = this.props.devices.map(this.myFunction);
            this.setState({
                devices_table: devices_table
            })
        }
    }

    myFunction = (value,index,array) => {
        let device = {};

        device.device = value;
        device.index = index + 1;
        device.version = '';

        apiGetDeviceVersion(value.identifier)
            .then((res,deviceid = value.identifier) => {
                let devices_table = this.state.devices_table;
                let objIndex = devices_table.findindex(d => d.device.identifier === deviceid)
                devices_table[objIndex].version = res.valueReported;
                this.setState({
                    devices_table: devices_table
                })
            })
            .catch(e => {
                console.log(e)
            })

        return device;
    }

    render() {
        const devices = this.state.devices_table;
        if (isEmpty(devices)) {
            return (<div></div>)
        }
        let columns = [
            {
                text: "#",datafield: "index",sort: true
            },{
                text: "ID",datafield: "device.identifier",{
                text: "Name",datafield: "device.name",{
                text: "Status",datafield: "device.status",{
                text: "Version",datafield: "version",sort: true
            }
        ];

        return (
            <div>
                <BootstrapTable keyField={"device.identifier"} data={devices} columns={columns}></BootstrapTable>
            </div>
        )
    }
}

export default DeviceTable

解决方法

componentDidUpdate(prevProps) {
   if (prevProps.devices !== this.props.devices) {
            *let devices_table* = this.props.devices.map(this.myFunction);
            this.setState({
                devices_table: devices_table
            })
        }
}

可能由于响应作为异步功能而工作(由于API)。因此,您必须等待响应使其可用,否则“ devices_table”将保持为空或未定义,并且不会导致数据可视化。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...