问题描述
我正在尝试从查询字符串中提取数据,然后调用 API 并正确呈现组件和过滤器,但状态是异步工作的,我不能这样做:
state = {
currentPage: 1,
sort: {
name: '',
salary: '',
},
};
componentDidMount() {
this.handlePullSortFromQuery();
this.handlePullPageFromQuery();
this.handleUploadData();
}
相反,我尝试在constructor()
使用this.handlePullSortFromQuery()
和this.handlePullPageFromQuery()
constructor()
:
constructor(props) {
super(props);
this.state = {
currentPage: 1,
sort: {
name: '',
salary: '',
},
};
this.handlePullSortFromQuery();
this.handlePullPageFromQuery();
}
componentDidMount() {
this.handleUploadData();
}
但是我的状态根本没有更新,我收到了这个警告:
警告:无法在尚未安装的组件上调用 setState。
这是一个空操作,但它可能表明您的应用程序中存在错误。
相反,直接分配给this.state
或定义一个state = {};
_temp 组件中具有所需状态的类属性。
那么它是如何工作的呢? 我该如何解决问题? 我应该在什么地方提取查询字符串数据?
1楼
Sood
1
已采纳
2019-02-12 13:05:55
事实上,状态是异步工作的,但是将调用 setState 的函数放在构造函数中并不是解决方案。
您可以使用 async/await 或在回调中调用您的函数以便按顺序执行它们。
async componentDidMount() {
await this.handlePullSortFromQuery();
await this.handlePullPageFromQuery();
await this.handleUploadData();
}
2楼
Artem Balamutyuk
0
2019-02-12 13:09:04
为了解决这个问题,我只是在构造函数中调用函数,返回值而不是setState
,然后作为函数调用的结果初始化状态。
constructor(props: any) {
super(props);
const { page, sort } = parseQueryString(props.location.search);
const currentPage = this.handlePullPageFromQuery(page);
const sortQueryObject = this.handlePullSortFromQuery(sort);
this.state = {
currentPage,
sort: sortQueryObject,
};
}
componentDidMount() {
this.handleUploadData();
}