我正在尝试从查询字符串中提取数据,然后调用 API 并正确渲染组件和过滤器,但状态是异步工作的,我不能这样做:
state = {
currentPage: 1,
sort: {
name: '',
salary: '',
},
};
componentDidMount() {
this.handlePullSortFromQuery();
this.handlePullPageFromQuery();
this.handleUploadData();
}
相反,我尝试在 constructor()
中使用 this.handlePullSortFromQuery()
和 this.handlePullPageFromQuery()
:
constructor(props) {
super(props);
this.state = {
currentPage: 1,
sort: {
name: '',
salary: '',
},
};
this.handlePullSortFromQuery();
this.handlePullPageFromQuery();
}
componentDidMount() {
this.handleUploadData();
}
但是我的状态根本没有更新,我收到了这个警告:
警告:无法在尚未安装的组件上调用 setState。这是一个空操作,但它可能表示您的应用程序中存在错误。相反,直接分配给 this.state
或在 _temp 组件中定义具有所需状态的 state = {};
类属性。
那么它是如何工作的呢?我该如何解决这个问题?我应该在什么地方提取查询字符串数据?
最佳答案
确实状态是异步工作的,但是将调用 setState 的函数放在构造函数中无论如何都不是解决方案。
您可以使用 async/await 或在回调中调用您的函数以便按顺序执行它们。
async componentDidMount() {
await this.handlePullSortFromQuery();
await this.handlePullPageFromQuery();
await this.handleUploadData();
}
关于javascript - 从查询字符串中提取数据,然后调用 API 和呈现组件的最佳位置是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54649834/