首页 > 解决方案 > React setState 不会更新我的表的视图

问题描述

即使状态正在更新,我也很难更改 Bootstrap 表的视图。

我做了一些研究,发现this.setState是异步的,所以我确保检查并更改回调函数中的状态;但是,即使在回调函数中,状态也会改变。如果这仍然是this.setState问题,我会感到困惑。

export class EduInfo extends React.Component {

constructor(props){
    super(props);

    this.state = {
        education: this.props.incomingClass.degreeEdu
    };
    
    this.updateEdu = this.updateEdu.bind(this);
}

updateEdu = (e) => {
    e.preventDefault();
    let newEdu = {...this.props.incomingClass};
    BackEndRestService.updateEdu(newEdu).then(data => {
        this.setState({
            education: data.degreeEdu,
        }, () => console.log(data));
    }).catch(e => {
    console.log(e);
    });
}

render(){
    return(
        <BootstrapTable
        hover
        condensed={true}
        bootstrap4={true}
        keyField={'id'}
        data={this.state.education}
        columns={this.columns}
        />
    );

}

}

一旦状态更新,它应该重新渲染和更新 Bootstrap 表中的'data={this.state.education}'。但是,表格视图没有改变。

标签: reactjsreact-bootstrapreact-bootstrap-table

解决方案


在您的返回函数中有类似的内容:

   return(
    { (this.state.readyToShow)?
       <div>
              <BootStrapTable ... 
              />
       </div>
        : ''
    } );

设置 ReadyToShow 的状态后,您应该能够看到带有信息的 Bootstrap 表。并且仅在您为数据发送的请求的响应结束时更改状态 readyToShow 的状态(可能使用回调)。我看到的问题是您的数据可能不会在反应渲染之前到达。这种情况在我身上发生过很多次。例如,如果使用 axios 获取数据:

val axios4data = axios.get(*some link to the controller to get data*).then(function (response) {

 ...
  *make something with the response and set the state of the varable for the data table of the bootstrap table*

     self.setState({education: `dataFromResponse`}, 
                      () =>
                         {
                              *execute call back or code to set the state of readyToShow to true*  
                         }
                  )



});

在使用 setState 的回调设置教育状态后,更新 ReadyToShow 的状态非常重要。


推荐阅读