useEffect清理功能未称为“响应本机”

时间:2020-09-11 13:20:19

标签: reactjs react-native use-effect

我一直试图使用清除功能来取消API调用,即用户在解决请求之前按了“后退”按钮。 但是,我仍然收到相同的错误“警告:无法在已卸载的组件上执行React状态更新”。 我正在使用访存功能,添加了abortController,但仍然收到相同的警告。

import React, { useState, useEffect, useReducer, useContext } from "react";
import { ActivityIndicator } from "react-native";
import AllThumbnails from "../components/AllThumbnails";
import reducer from "../functions/reducer";
import { lightColors, darkColors } from "../constants/Colors";
import { ThemeContext } from "../context/context";
import ScreenContainer from "../components/UI/ScreenContainer";

export default function AllCatScreen(props) {
    const { navigation, route } = props;
    const [categories, setCategories] = useState([]);
    const [state, dispatch] = useReducer(reducer, { catPage: 1 });
    const [theme] = useContext(ThemeContext);
    const { taxonomy } = route.params;

    useEffect(() => {
        const abortCtrl = new AbortController();
        const opts = { signal: abortCtrl.signal };
        let isActive = true;

        fetch(`${siteURL}/wp-json/wp/v2/${taxonomy.endPoint}`, opts)
            .then((response) => response.json())
            .then((res) => {
                if (isActive) {
                    setCategories([...categories, ...res]);
                }
            })
            .catch((err) => console.log(err));
        return function cleanup() {
            isActive = false;
            console.log(isActive);
            abortCtrl.abort();
        };
    }, []);

    if (categories.length == 0) {
        return (
            <ScreenContainer notYet={true}>
                <ActivityIndicator size="large" color={theme.colors.text} />
            </ScreenContainer>
        );
    } else {
        return (
            <ScreenContainer notYet={false}>
                <AllThumbnails
                    data={categories}
                    navigation={navigation}
                    catThumb={true}
                    action={[state, dispatch]}
                    fetchData={fetchData}
                />
            </ScreenContainer>
        );
    }
}

我已阅读到,react native应该支持AbortController。我使用的是Expo SDK 38,但即使在清理功能中,控制台也无法记录。有人知道怎么了吗?

0 个答案:

没有答案