首页 > 解决方案 > axios调用给无限循环

问题描述

我需要获取一些数据并设置状态,但它给了我无限循环,我不知道如何解决这个问题。

我的 Routes.tsx 中的示例:

// get all posts
    useEffect(() => {
        Axios.get('/api/posts', config)
            .then(res => setAllPosts(res.data))
            .catch(err => console.log(err))
    }, [config]);

如果我不依赖'config',它只会在刷新时显示结果,但它不会给我无限循环。

这是我的项目:https ://github.com/marinavrataric/social_network

标签: javascriptreactjsaxios

解决方案


尝试使用 useStata[] 和 useEffect[]

   const [data, setData] = useState({ hits: [] });
     
      useEffect(async () => {
        const result = await axios.get('/api/posts', config)
            .then(res => setAllPosts(res.data))
            .catch(err => console.log(err))
     
        setData(result);
      }, []);
     
      return (
        <ul>
          {data.posts.map(item => (
// stuff
          ))}
        </ul>
      );

推荐阅读