reactjs - 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}'。但是,表格视图没有改变。
解决方案
在您的返回函数中有类似的内容:
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 的状态非常重要。
推荐阅读
- c# - 我的 ASP.NET MVC 应用程序中的 Quartz 调度程序仅在 IIS 服务器上刷新网页/应用程序后才执行作业
- c# - 如何在 Xamarin Form 项目中获取 XAML 文件中描述的控件?
- regex - 匹配一行中的第 n 个单词
- sql - 有没有办法让这个查询成为一个循环或更有效?
- python - 使用分类变量运行 F 检验
- python - 将 pageToken 与 Google Analytics Reporting API v4 和 Python 结合使用
- verilog - 总是敏感列表中的异或。Verilog
- react-native - 执行失败:react-native-fbsdk:compileReleaseJavaWithJavac'
- python - Python Bokeh - HoverTool:图形的坐标而不是数据点
- c++ - 我需要将数组声明为静态局部变量吗?