等待反应中的函数

时间:2021-05-01 11:40:36

标签: javascript reactjs async-await

我有一个问题,我的函数在另一个函数结束之前运行。 我尝试在 GetEntries 中运行函数 GetCategories,但这对我不起作用。

GetEntries 仅适用于空字符串,因为函数执行得太早。虽然 useEffect 函数中有类别,但该函数不是 rerender。请帮忙。

import ...


export default function CFramework() {
  const year = GetYears();
  const title = GetCategories();
  const entries = GetEntries(title);
  const factor = GetFactor(title);

  return 
    <>
      <p>{year}</p>
      <p>Title: {title}</p>
      <p>Entries: {entries}</p>
      <p>Factor: {factor}</p>
   </>

获取类别:

import { useState, useEffect } from "react";
import Parse from "parse";

function GetCategories() {
  const [categories, setCategories] = useState([]);

  useEffect(() => {
    getCategories();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function getCategories() {
    const Categories = Parse.Object.extend("BerechnungsKategorie");
    const query = new Parse.Query(Categories);
    await query.find().then(function (results) {
      results.forEach((e) => {
        categories[parseInt(e.get("ID"))] = e.get("Name");
      });
    });
    setCategories([...categories]);
  }
  return categories;
}

export default GetCategories;

获取因子:

import { useState, useEffect } from "react";
import Parse from "parse";
import GetCategories from "./GetCategories";

export default function GetEntries(categories) {
  const [entries, setEntries] = useState([]);


  useEffect(() => {
    async function getValues() {
      categories.forEach((c, index) => {
        getEntries(c, index);
      });

      async function getEntries(category, index) {
        var temp = [];
        var q = new Parse.Query("BerechnungsKategorie");
        q.equalTo("Name", category);
        var results = await q.find();
        results.forEach((element, index) => {
          var q = new Parse.Query("BerechnungsEintrag");
          q.equalTo("Kategorie", category);
          q.find().then(function (category) {
            category.forEach((e, index) => {
              temp[index] = e.get("Name");
            });
            entries[index] = temp;
            if (entries.length === categories.length) {
              setEntries([...entries]);
            }
          });
        });
      }
    }
    getValues();
    console.log(categories);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, categories);

  return entries;
}

2 个答案:

答案 0 :(得分:1)

如果要全局持久化状态,请不要将反应功能组件用作普通功能或使用反应上下文

const [categories, setCategories] = useState([]);
    const [categories, setCategories] = useState([]);
      const [entries, setEntries] = useState([])
    
      const fetchData = async () => {
        const title = await getCategories();
        const entries = getEntries(title); // create function accroiding to that
      };
    
      useEffect(() => {
        fetchData();
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [categories]);
    ...

答案 1 :(得分:1)

另一个答案的回调版本:

export default function CFramework() {
  const [categories, setCategories] = useState([]);
  const [entries, setEntries] = useState([]);

  useEffect(() => {
    const title = GetCategories().then(() => {
       // wait for GetCategories=^
        const entries = GetEntries(title);
    });
  }, []);

  return 
    <>
      <p>{year}</p>
      <p>Title: {title}</p>
      <p>Entries: {entries}</p>
      <p>Factor: {factor}</p>
   </>
}

附注:您需要调整实用函数/服务以返回承诺