【问题标题】:How to filter API data in sanity.io using react.js?如何使用 react.js 过滤 sanity.io 中的 API 数据?
【发布时间】:2021-08-19 22:28:30
【问题描述】:

您好,我是社区的新手,正在学习这里的工作原理。请尝试通过我蹩脚的英语理解。

假设 API 中有 200 条数据,但我只想将任意 4 条随机数据拉到前端。更清楚地说,这些数据是来自 sanity.io 的博客文章,在 React.js 中使用 groq ql。这是显示来自 API 的所有数据的代码。我尝试过slice 功能,但没有奏效。

const SideBarBlog = () => {
  const [postData, setPost] = useState(null);
 
  useEffect(() => {
    sanityClient
      .fetch(
        `*[_type=="post"]{
        title,
        slug,
        mainImage{
          asset->{
            _id,
            url
          },
          alt,
          
        }
      }`
      )
      .then((data) => setPost(data))
      .then((data) => console.log(postData))

      .catch(console.error);
  }, []);

return (
    <>
      {postData &&
        postData.map((post, index) => (
       
            <div className="row sidebar-blog mb-4 p-3" key={index}>
              <div className="col-md-8">
                {/* sideblog title */}
                <p className="sidebolg-blogtitle mb-1">{post.title}</p>
              </div>
            </div>
         
        ))}
    </>
  );
};

export default SideBarBlog;

【问题讨论】:

  • .then((data) =&gt; setPost(data)),你可以在setPost之前做任何你想做的事情

标签: reactjs sanity groq


【解决方案1】:

用帖子设置你的状态后,你可以像这样访问数组中的随机帖子:

const postData = [{ post: "some post obj" }, { post: "another post obj" },  ];

const random = Math.floor(Math.random() * postsData.length); 
postData[random] //this returns a  random post

有了这个,您现在可以访问随机帖子并创建一个长度为 4 的新数组,或者您希望这样做

【讨论】:

    猜你喜欢
    • 2020-01-21
    • 2022-10-16
    • 1970-01-01
    • 2018-01-24
    • 2022-01-25
    • 2021-05-09
    • 2019-06-15
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多