React 中 fetch 调用后的清理函数

问题描述 投票:0回答:1
const[imageContainer,setImageContainer] = useState([])
    const navigate = useNavigate();
    useEffect(()=>{
        Promise.all([
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
            fetch("https://www.themealdb.com/api/json/v1/1/random.php").then(response=>response.json()),
          ]).then(response=>setImageContainer(response.map(recipe=>{
            return recipe.meals[0]
          })))
    },[])

你好,我对 React 还比较陌生。到目前为止,我了解到,在使用 useEffect 和返回函数后,您应该始终进行清理,以免减慢应用程序的速度。但我不确定在 fetch 调用后如何执行此操作。

reactjs react-hooks fetch-api
1个回答
0
投票

清理实际上通常是针对订阅(如事件处理程序)、计时器或其他副作用;这样做是为了防止内存泄漏。然而对于 fetch 调用,情况有所不同。如果组件在请求完成之前卸载,则更多的是取消请求,以避免在未安装的组件上设置状态。

这是您应该如何处理获取请求清理的方式:

useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;

    Promise.all([
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
        fetch("https://www.themealdb.com/api/json/v1/1/random.php", { signal }).then(response => response.json()),
    ]).then(response => setImageContainer(response.map(recipe => recipe.meals[0])))
     .catch(error => {
         if (error.name === 'AbortError') {
             console.log('Fetch aborted');
         } else {
             console.error('Fetch error:', error);
         }
     });

    return () => {
        controller.abort(); // This will cancel the fetch requests when the component unmounts
    };
}, []);

使用

AbortController
,其信号被传递到每个获取请求。
controller.abort();
useEffect
的返回函数内执行。

参考:

中止控制器

使用效果

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