第一次单击后表不呈现

时间:2019-08-30 17:02:44

标签: javascript reactjs components axios rendering

当我单击导航按钮时,将加载表数据,但第二次单击时将不加载表数据,但每次在React js中单击时都会加载表中的数据

我已将代码放入componentdidMount() {}中,以便每次加载时都将其加载。我做了一个异步功能,可以加载表格并设置标题。

{this.state.numofbugs.map((data)=> {
    return (
        <li key={data}>
            <Link to={'/applogs/' + data}
                     className="waves-effect" className={this.props.location.pathname === '/applogs/' + data ? 'active': ''}>
                <span className="font-size waves-effect" >{data}</span>
            </Link>
        </li>
    )
})} 

在其呈现的文件中

componentDidMount() {
    if (this.props.location.pathname.includes('app_')) {
        this.showTable(this.props.location.pathname.split('/')[2]);
    }
}

async showTable(col_name) {
    // empty data
    this.state.logtable = []
    let conf = { headers: { Authorization: 'Bearer ' + localStorage.getItem('session') }}
    Axios.get(links.baseURL + 'sample?collection=' + col_name, conf).then((response) => {
        // get headers
        this.state.tableHeaders = [
            Object.keys(response.data.result[0])[0], 
            Object.keys(response.data.result[0])[1],
            Object.keys(response.data.result[0])[2],
            Object.keys(response.data.result[0])[3],
        ]

        Object.keys(response.data.result).map((key) => {
            this.state.logtable[key] = response.data.result[key];
            this.state.logtable[key]['key'] = key.toString()
        }); 
        this.setState({'logtable': this.state.logtable});
    });
}

我希望每次在表中单击按钮时都会在我的表中获取数据,但是在单击表中折叠数据Lad的选项卡之后又在第二次将数据加载到标记而不是表中

1 个答案:

答案 0 :(得分:1)

第一件事,您不需要清空状态,

this.state.logtable = []

如果要用新状态替换现有状态,只需用新数据设置状态。

另一个问题是,您正在像这样直接更改状态

this.state.tableHeaders = [
    Object.keys(response.data.result[0])[0], 
    Object.keys(response.data.result[0])[1],
    Object.keys(response.data.result[0])[2],
    Object.keys(response.data.result[0])[3],
]

还有这个

Object.keys(response.data.result).map((key) => {
    this.state.logtable[key] = response.data.result[key];
    this.state.logtable[key]['key'] = key.toString()
}); 

您应利用局部变量创建临时数组,然后将其设置为您的状态,例如

async showTable(col_name) {

    let conf = { headers: { Authorization: 'Bearer ' + localStorage.getItem('session') }}
    Axios.get(links.baseURL + 'sample?collection=' + col_name, conf).then((response) => {
        // get headers
        let tableHeaders = Object.keys(response.data.result[0]).map((key,index) => index <=3 && key.toString())

        let logtable = Object.keys(response.data.result).map((key) => ({
            logtable[key] : response.data.result[key];
            logtable[key]['key'] : key.toString()
        })); 
        this.setState({logtable, tableHeaders});
    });
}