【问题标题】:How to Async/Await using useEffect for fetching data? [duplicate]如何使用 useEffect 异步/等待来获取数据? [复制]
【发布时间】:2021-06-06 21:05:37
【问题描述】:

我查找了一些问题,但未能解决此问题。我正在尝试将async and await 添加到我正在获取数据的useEffect 中。

另外,如何在先加载数据之前添加一个简单的加载文本?

我的代码:

import { useEffect, useState } from "react";

import { Link } from "react-router-dom";

import SanityClient from "sanity.client";

const AllPosts = () => {
  const [posts, setPosts] = useState(null);

  useEffect(() => {
    const postsQuery = `
    *[_type == 'post'] {
      _id,
      title,
      slug,
      mainImage {
        alt,
        asset -> {
          _id,
          url
        }
      }
    }
  `;

    SanityClient.fetch(postsQuery)
      .then((data) => setPosts(data))
      .catch(console.error);
  }, []);

  return (
    <>
      <h2>Blog Posts</h2>
      <h3>Welcome to my blog</h3>
      {posts &&
        posts.map((post) => (
          <Link key={post._id} to={`/blog/${post.slug.current}`}>
            <img src={post.mainImage.asset.url} alt={post.mainImage.alt} />
            <h2>{post.title}</h2>
          </Link>
        ))}
    </>
  );
};

export default AllPosts;

【问题讨论】:

  • 你在等待什么?你已经在使用 Promise 链了。

标签: reactjs sanity


【解决方案1】:

这里是异步等待的方法。你试过吗?

import { useEffect, useState } from "react";

import { Link } from "react-router-dom";

import SanityClient from "sanity.client";

const AllPosts = () => {
  const [posts, setPosts] = useState(null);

  const fetchData = async (postsQuery) => {
    try {
      const data = await SanityClient.fetch(postsQuery);
      if (data) {
        setPosts(data);
      }
    } catch(error) {
      console.log(error);
    }
  }

  useEffect(() => {
    const postsQuery = `
    *[_type == 'post'] {
      _id,
      title,
      slug,
      mainImage {
        alt,
        asset -> {
          _id,
          url
        }
      }
    }
  `;

    fetchData(postsQuery);
  }, []);

  return (
    <>
      <h2>Blog Posts</h2>
      <h3>Welcome to my blog</h3>
      {posts &&
        posts.map((post) => (
          <Link key={post._id} to={`/blog/${post.slug.current}`}>
            <img src={post.mainImage.asset.url} alt={post.mainImage.alt} />
            <h2>{post.title}</h2>
          </Link>
        ))}
    </>
  );
};

export default AllPosts;

【讨论】:

  • useEffect 钩子回调是 100% 同步的,它们不能声明为 async,因为隐式返回的 Promise 被解释为返回的钩子清理函数。
  • 哦,是的!抱歉,刚刚更新了上面的代码。
  • 由于问题已关闭,我无法发布我的答案,但我在另一个问题中回答了:stackoverflow.com/questions/53332321/…
猜你喜欢
  • 2021-05-25
  • 2021-07-07
  • 2019-07-01
  • 2022-07-06
  • 2020-10-03
  • 1970-01-01
  • 2020-04-08
  • 2020-12-03
  • 2021-11-20
相关资源
最近更新 更多