【问题标题】:How to wait for one API call to finish before initiating another in React?如何在 React 中启动另一个 API 调用之前等待一个 API 调用完成?
【发布时间】:2020-08-13 07:00:20
【问题描述】:

所以在我的 React 应用程序中,我使用 fetch API 来获取“线程”项目列表,并使用另一个调用来获取“类别”列表。我的“线程”列表会立即呈现到 DOM 中,并且在一个 DOM 元素中它取决于“类别”列表的存在。它大部分时间都有效,但偶尔会在填充“类别”之前获取“线程”,并且尝试访问“类别”的 DOM 元素会抛出错误,指出我正在尝试访问未定义元素的属性。 我基本上需要找到一种在获取“线程”之前等待“类别”获取和填充的方法。

useEffect(() => {
  getCategories();
  getThreads();
}, []);

function getThreads() {
loadThreads(categoryId, Feed.threadPage++, 10)
  .then((r) => {
    if (r.status === 200) {
      r.text().then((responseBody) => {
        let responseBodyObject = JSON.parse(responseBody);
        if (responseBodyObject.threads.length === 0)
          setHasMoreThreads(false);
        setThreads(threads.concat(responseBodyObject.threads));
      });
    } else {
      toast.error("Failed to fetch threads");
    }
  })
  .catch((e) => toast.error("Failed to fetch threads."));
}

function getCategories() {
loadCategories()
  .then((r) => {
    if (r.status === 200) {
      r.text().then((responseBody) => {
        let responseBodyObject = JSON.parse(responseBody);
        setCategories(responseBodyObject.categories);
      });
    } else {
      toast.error("Failed to load the categories");
    }
  })
  .catch((e) => toast.error("Failed to load the categories"));
}

在我的 DOM 中,我有:

{threads.map((v, i) => (
            <div key={i}>
              <div
                className={classes.feedThreadBox}
                onClick={(e) => console.log(v)}
              >
                <h5 style={{ marginBottom: 0 }}>
                  {v != undefined && v.title}
                </h5>
                <i
                  className="fa fa-circle fa-xs"
                  style={{
                    color:
                      "#" +
                      categories.find(
                        (category) => category.id === v.categoryId
                      ).color,
                    fontSize: 10,
                  }}
                ></i>{" "}
                {
                  categories.find(
                    (category) => category.id === v.categoryId
                  ).name
                }
              </div>
              <hr></hr>
            </div>
          ))}

如何确保在“threads.map”呈现之前填充“类别”?

【问题讨论】:

  • 你可以在你的情况下使用async/await

标签: javascript reactjs fetch


【解决方案1】:

你应该使用异步/等待:

  • 将 async 关键字放在 getCategories() 函数前面

  • 在函数体中使用 await

您可以找到更多使用信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多