【问题标题】:How to handle async data in ComponentDidUpdate?如何处理 ComponentDidUpdate 中的异步数据?
【发布时间】: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 ...)

标签: reactjs api redux


【解决方案1】:

控制台日志总是首先执行,因为searchResults 是异步的。您需要做的是在searchResults 中返回一个承诺:

const searchResults = (keywords) => {
 // fetch with the keywords and return the promise
 // or any promise that resolves after your search is completed
 return fetch(...);
};

componentDidUpdate(prevProps, prevState) {
    if (
      this.state.searchClick &&
      prevState.searchClick !== this.state.searchClick
    ) {
      // send get request to fetch data
      this.props.searchResults(this.state.keyword).then(() => {
        //Update searchClick state
        this.setState({ ...this.state, searchClick: false });
        // console log the result data
        console.log(this.props.results);
      });
    }
  }


【讨论】:

    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多