我正在尝试从查询字符串中提取数据,然后调用API并正确呈现组件和过滤器,但状态是异步工作的,我不能这样做:
state = {
currentPage: 1,
sort: {
name: '',
salary: '',
},
};
componentDidMount() {
this.handlePullSortFromQuery();
this.handlePullPageFromQuery();
this.handleUploadData();
}
相反,我尝试在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
或在_temp组件中定义具有所需状态的state = {};
类属性。
它是如何工作的?我怎么解决这个问题?在什么地方我应该提取查询字符串数据?
实际上,状态是异步工作的,但是将你的函数调用到构造函数中的setState并不是解决方案。
您可以使用async / await或在回调中调用函数,以便按顺序执行它们。
async componentDidMount() {
await this.handlePullSortFromQuery();
await this.handlePullPageFromQuery();
await this.handleUploadData();
}
要解决这个问题,我只需在构造函数中调用函数,返回值而不是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();
}