【发布时间】:2021-09-26 10:34:46
【问题描述】:
我是 React 新手,现在有一些问题。
单击按钮时,我使用 componentDidUpdate 获取数据。我用 redux 管理结果数据。看起来 componentDidUpdate 是异步函数,因为“console.log”总是在 fetch 函数完成之前先执行。所以我第一次点击按钮时总是在控制台中得到 []。
假设我在单击按钮时想要执行 2 个操作。首先获取数据,然后使用该数据并传递给另一个操作。在执行 console.log 之后如何等到获取数据完成?请帮帮我。
state = {
searchClick: false,
keyword: "pizza",
};
componentDidUpdate(prevProps, prevState) {
if (
this.state.searchClick &&
prevState.searchClick !== this.state.searchClick
) {
// send get request to fetch data
this.props.searchResults(this.state.keyword);
//Update searchClick state
this.setState({ ...this.state, searchClick: false });
// console log the result data
console.log(this.props.results);
}
}
【问题讨论】:
-
this.props.searchResults().then( ... update the state ...)