React Native 如何通过 api 调用传递 id?

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

我有一个api调用,比如:http://192.168.1.68:8000/api/categories/2/

当然id可以是任意数字。所以我尝试在 api 调用中传递 id,例如:

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;
    }
};
 

我在上下文中使用函数:

export const CategoryContext = createContext();

export const CategoryContextProvider = ({ children }) => {
    
    const [subCategoryList, setSubCategoryList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [] = useState([]);



    const retrieveSubCategories = () => {
        setLoading(true);
        setTimeout(() => {
            fetchSubCategoryData()              
                .then((results) => {
                    setLoading(false);
                    setSubCategoryList(results.subcategories);
                })
                .catch((err) => {
                    setLoading(false);
                    setError(err);
                });
        });
    };

    useEffect(() => {
        retrieveSubCategories();
    }, []);

    return (
        <CategoryContext.Provider
            value={{
            
                subCategoryList,
                loading,
                error,
            }}>
            {children}
        </CategoryContext.Provider>
    );
};;

但这失败了:

获取操作出现问题:,[错误:网络 反应不好]

但这行得通:

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

问题:如何在api调用中动态传递id?

javascript reactjs react-native
© www.soinside.com 2019 - 2024. All rights reserved.