javascript 如何通过react native调用API传递id?

qacovj5a  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(135)

我有一个react原生应用,我尝试通过API调用传递id,后端我使用django framework,如果我硬编码,它就可以工作,但是如果我传递id,我会得到这个错误:

There was a problem with the fetch operation:, [Error: Network response was not ok]

这是我的服务电话

export const fetchSubCategoryData = async (id) => {
    try {
        const response = await fetch(`http://192.168.1.68:8000/api/categories/${id}/`, {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
        });
        if (!response.ok) {
            throw new Error("Network response was not ok");
        }

        return await response.json();
    } catch (error) {
        console.error("There was a problem with the fetch operation:", error);
        throw error;
    }
};

但如果我这么做:

const response = await fetch(`http://192.168.1.68:8000/api/categories/${2}/`

那就成功了
这是触发API调用的组件:

export const SubCategoryScreen = ({ route }) => {
    const [subCatgoryList, setSubCategoryList] = useState([]);

    useEffect(() => {
        fetchSubCategoryData(route.category).then((data) => {
            setSubCategoryList(data);
        });
    }, [route.category]);

    return (
        <SafeArea>
            <CategoryList
                data={subCatgoryList}
                renderItem={({ item }) => {
                    return (
                        <TouchableOpacity onPress={() => console.log(item)}>
                            <Spacer position="bottom" size="large">
                                <SubCategoryInfoCard category={item} />
                            </Spacer>
                        </TouchableOpacity>
                    );
                }}
                keyExtractor={(item) => item.id}
            />
        </SafeArea>
    );
};

因此,在此组件中,您将导航到SubCategoryScreen:

export const CategoryScreen = ({ navigation }) => {
    const { loading, error, categoryList } = useContext(CategoryContext);
    return (
        <SafeArea>
            {loading && (
                <LoadingContainer>
                    <ActivityIndicator animating={true} color={MD2Colors.green200} />
                </LoadingContainer>
            )}
            <Search />
            <CategoryList
                data={categoryList}
                renderItem={({ item }) => {
                    console.log(item.id);
                    return (
                        <TouchableOpacity
                            onPress={() => navigation.navigate("groepen", { subcategories: item.id })}>
                            <Spacer position="bottom" size="large">
                                <CategoryInfoCard category={item} />
                            </Spacer>
                        </TouchableOpacity>
                    );
                }}
                keyExtractor={(item) => item.id}
            />
        </SafeArea>
    );
};

来自后端的API调用看起来:

http://192.168.1.68:8000/api/categories/2/

问:如何在url中传递id作为参数?
subcategories是一个对象数组:

Object {
  "animals": Array [],
  "category": null,
  "description": "vogels",
  "eaza": "",
  "id": 2,
  "images": "http://192.168.1.68:8000/media/photos/categories/birds.png",
  "legislation": "",
  "name": "vogels",
  "review": "",
  "subcategories": Array [
    Object {
      "description": "roofvogels",
      "id": 3,
      "images": "http://192.168.1.68:8000/media/photos/categories/predator_ETI4KPC.jpg",
      "name": "roofvogels",
    },
    Object {
      "description": "parkieten",
      "id": 5,
      "images": "http://192.168.1.68:8000/media/photos/categories/01-smartest-birds-NationalGeographic_2467639.webp",
      "name": "parkieten",
    },
    Object {
      "description": "",
      "id": 12,
      "images": "http://192.168.1.68:8000/media/media/photos/categories/seagull.png",
      "name": "meeuwen",
    },
  ],
}

所以我试着这样说:

export const SubCategoryScreen = ({ route }) => {
    const [subCatgoryList, setSubCategoryList] = useState([]);
    const [isLoading, setLoading] = useState(true);

    useEffect(() => {
        fetchSubCategoryData(route.params.subcategories).then((data) => {
            setLoading(false);
            console.log(data);
            setSubCategoryList(data);
        });
    }, [route]);

    return (
        <SafeArea>
            {isLoading && (
                <LoadingContainer>
                    <ActivityIndicator animating={true} color={MD2Colors.green200} />
                </LoadingContainer>
            )}
            <CategoryList
                data={subCatgoryList}
                renderItem={({ item }) => {
                    return (
                        <TouchableOpacity onPress={() => console.log(item)}>
                            <Spacer position="bottom" size="large">
                                <SubCategoryInfoCard subcategories={item} />
                            </Spacer>
                        </TouchableOpacity>
                    );
                }}
                keyExtractor={(item) => item.id}
            />
        </SafeArea>
    );
};

然后我仍然得到这个错误:

Invariant Violation: TaskQueue: Error with task : Tried to get frame for out of range index NaN
monwx1rj

monwx1rj1#

您的代码似乎有一个问题。
首先,在导航时将子类别参数传递给SubCategoryRoute

//You are passing {subcategories: item.id}
onPress={() => navigation.navigate("groepen", { subcategories: item.id })}>

然后,在将该参数发送到fetchData函数时,需要选择该特定参数

console.log(route.params) //See all params
    //You passed subcategories to this screen, this is where your ID is.
     fetchSubCategoryData(route.params.subcategories).then((data) => {
            setSubCategoryList(data);
        });
ippsafx7

ippsafx72#

通过传递datasubcategories属性(而不是整个data对象)进行修复:

setSubCategoryList(data.subcategories);

相关问题