javascript 如何在更新加载状态之前等待useEffect中的所有异步函数完成?

tcbh2hod  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(110)

我正在尝试从我的API接收图书ID列表。对于每个图书ID,我想从Google的图书API获取其数据。一旦所有的图书信息已检索,我想为他们呈现div。但是,加载状态在每次提取完成之前被改变。有人能解释一下为什么会这样吗

function ReadingListPage({ userID }) {
  const [books, setBooks] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  let bookIds = [];

  useEffect(() => {

    const getBookInfo = async (bookId) => {
      const response = await fetch(`https://www.googleapis.com/books/v1/volumes/${bookId}`);
      const resJson = await response.json();
      setBooks([...books, resJson]);
      Promise.resolve();
    };

    const getBookIds = async () => {
      const response = await fetch(`//localhost:3001/user/reading_list/${userID}`);
      const resJson = await response.json();
      bookIds = resJson;

      await Promise.all(
        bookIds.map(async (bookId) => {
          await getBookInfo(bookId);
        })
      );

      setIsLoading(false);
    };

    getBookIds();
  }, []);

  return (
    <ContentLayout>
      <BookDisplay>
        {!isLoading && <BookSection name={"Your Reading List"} books={books}></BookSection>}
      </BookDisplay>
    </ContentLayout>
  );
}
cvxl0en2

cvxl0en21#

我想在所有的书都装上之前它是不会显示的。只是你的账本太多了。我试着这样重写:

useEffect(() => {
  const getBookInfo = async (bookId) => {
    const response = await fetch(`https://www.googleapis.com/books/v1/volumes/${bookId}`);
    const book = await response.json();
    return book;
  };

  const getBookIds = async () => {
    const response = await fetch(`//localhost:3001/user/reading_list/${userID}`);
    const resJson = await response.json();
    bookIds = resJson;

    const books = await Promise.all(bookIds.map(async (bookId) => getBookInfo(bookId)));

    setBooks(books);

    setIsLoading(false);
  };

  getBookIds();
}, []);

这样,您只需为books设置一次新值,而不会覆盖它。

1rhkuytd

1rhkuytd2#

试试这个代码,希望对你有用

useEffect(() => {
  // ...

  const getBookInfo = async (bookId) => {
    const response = await fetch(`https://www.googleapis.com/books/v1/volumes/${bookId}`);
    const resJson = await response.json();
    setBooks(prevBooks => [...prevBooks, resJson]);
  };

  // ...
}, []);

相关问题