猿问

在第一次点击反应后表格不会呈现

当我点击导航按钮然后表格数据加载但在第二次点击表格数据不加载但数据加载在反应 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});

    });

}

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


慕村9548890
浏览 153回答 1
1回答

Smart猫小萌

首先,你不需要像这样清空你的状态,this.state.logtable = []如果你想用新的状态替换现有的状态,你可以简单地用新数据设置状态。另一个问题是,你直接改变你的 state,像这样this.state.tableHeaders = [&nbsp; &nbsp; Object.keys(response.data.result[0])[0],&nbsp;&nbsp; &nbsp; Object.keys(response.data.result[0])[1],&nbsp; &nbsp; Object.keys(response.data.result[0])[2],&nbsp; &nbsp; Object.keys(response.data.result[0])[3],]和这个Object.keys(response.data.result).map((key) => {&nbsp; &nbsp; this.state.logtable[key] = response.data.result[key];&nbsp; &nbsp; this.state.logtable[key]['key'] = key.toString()});&nbsp;您应该使用局部变量来创建临时数组,然后需要将它们设置为您的状态,例如,async showTable(col_name) {&nbsp; &nbsp; let conf = { headers: { Authorization: 'Bearer ' + localStorage.getItem('session') }}&nbsp; &nbsp; Axios.get(links.baseURL + 'sample?collection=' + col_name, conf).then((response) => {&nbsp; &nbsp; &nbsp; &nbsp; // get headers&nbsp; &nbsp; &nbsp; &nbsp; let tableHeaders = Object.keys(response.data.result[0]).map((key,index) => index <=3 && key.toString())&nbsp; &nbsp; &nbsp; &nbsp; let logtable = Object.keys(response.data.result).map((key) => ({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logtable[key] : response.data.result[key];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logtable[key]['key'] : key.toString()&nbsp; &nbsp; &nbsp; &nbsp; }));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; this.setState({logtable, tableHeaders});&nbsp; &nbsp; });}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答