如何用useState和promise解决这个问题?

问题描述 投票:0回答:1

Promice 正在重写钩子的值,我试图为我的帖子获得更多的值,但承诺继续用数据的值替换钩子的值

const loadNewProducts = async() =>{
            while(posts.length<15){
            await fetch (`http{loadLimit[0]}&limit=${loadLimit[1]}&sort=title%3Aasc`)           
            .then((res) => res.json())
            .then((data) => {
                data.data.map((data: { id: any; }) => {if (posts.includes((post: { id: any; }) => post.id!=data.id)||posts.length==0) {setPosts(posts => [...posts, data])}});
                setPosts(posts => posts.slice(-data.data.length));console.log(posts);
                
            })
            .catch((err) => {
                console.log(err.message);
            });
            loadLimit = [loadLimit[0],loadLimit[1]+1];if(loadLimit[1]==13){loadLimit = [loadLimit[0]+1,1]}}}



        // eslint-disable-next-line react-hooks/exhaustive-deps
        useEffect(() => {{loadNewProducts();console.log(posts);loadNewProducts();console.log(posts)}}, [])

我尝试了很多方法来解决这个问题,但没有任何帮助

reactjs promise hook
1个回答
0
投票

尝试使用如下所示的 useRef -

import { useEffect, useState, useRef } from "react";

const loadNewProducts = async (loadLimit, postsRef, setPosts) => {
  while (postsRef.current.length < 15) {
    try {
      const res = await fetch(`http{loadLimit[0]}&limit=${loadLimit[1]}&sort=title%3Aasc`);
      const data = await res.json();
      const newPosts = data.data.filter((item) => !postsRef.current.some((post) => post.id === item.id));
      if (newPosts.length > 0) {
        setPosts((prevPosts) => {
          const updatedPosts = [...prevPosts, ...newPosts];
          postsRef.current = updatedPosts;
          return updatedPosts;
        });
      }

      loadLimit = [loadLimit[0], loadLimit[1] + 1];
      if (loadLimit[1] === 13) {
        loadLimit = [loadLimit[0] + 1, 1];
      }
    } catch (err) {
      console.log(err.message);
    }
  }
};

const YourComponent = () => {
  const [posts, setPosts] = useState([]);
  const postsRef = useRef(posts);

  useEffect(() => {
    const loadLimit = [0, 1];
    loadNewProducts(loadLimit, postsRef, setPosts);
  }, []);

  return (
    <div>
      {posts.map((post, index) => (
        <div key={index}>{post.title}</div>
      ))}
    </div>
  );
};

export default YourComponent;

让我知道它是否有效。将

YourComponent
更改为您的组件

© www.soinside.com 2019 - 2024. All rights reserved.