英文:
How to load data from api call in card with react native?
问题
如何返回“roofvogels”和“parkieten”两个项目?
要返回“roofvogels”和“parkieten”这两个项目,你需要遍历item.subcategories
数组,并为每个子类别创建一个单独的组件。以下是如何在SubCategoryScreen
组件中实现它的示例代码:
export const SubCategoryScreen = () => {
const { subCategoryList } = useContext(CategoryContext);
return (
<SafeArea>
<CategoryList
data={subCategoryList}
renderItem={({ item }) => (
<Spacer position="bottom" size="large">
{item.subcategories.map((subcategory) => (
<SubCategoryInfoCard key={subcategory.id} subcategory={subcategory} />
))}
</Spacer>
)}
keyExtractor={(item) => item.name}
/>
</SafeArea>
);
};
在这个示例中,我们使用了map
函数来遍历item.subcategories
数组中的每个子类别对象,并为每个子类别创建了一个SubCategoryInfoCard
组件。这将允许你在屏幕上呈现所有子类别,包括“roofvogels”和“parkieten”。
英文:
I have a react native app and I try to navigate to a card component where the data from a backend call has to be loaded. But untill now the data call has not been triggered from the backend.
So I have a service:
export const fetchSubCategoryData = async () => {
try {
const response = await fetch("http://192.168.1.68:8000/api/categories/2", {
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;
}
};
and a context:
export const CategoryContext = createContext();
export const CategoryContextProvider = ({ children }) => {
const [categoryList, setCategoryList] = useState([]);
const [subCategoryList, setSubCategoryList] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [] = useState([]);
const retrieveCategories = () => {
setLoading(true);
setTimeout(() => {
fetchCategoryData()
.then((results) => {
setLoading(false);
setCategoryList(results);
})
.catch((err) => {
setLoading(false);
setError(err);
});
});
};
const retrieveSubCategories = () => {
setLoading(true);
setTimeout(() => {
fetchSubCategoryData()
.then((results) => {
setLoading(false);
setSubCategoryList(results);
})
.catch((err) => {
setLoading(false);
setError(err);
});
});
};
useEffect(() => {
retrieveCategories();
}, []);
useEffect(() => {
retrieveSubCategories();
}, []);
return (
<CategoryContext.Provider
value={{
categoryList,
subCategoryList,
loading,
error,
}}>
{children}
</CategoryContext.Provider>
);
};
And the component from where I want to navigate to the other component:
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 }) => {
return (
<TouchableOpacity onPress={() => navigation.navigate("groepen", { category: item })}>
<Spacer position="bottom" size="large">
<CategoryInfoCard category={item} />
</Spacer>
</TouchableOpacity>
);
}}
keyExtractor={(item) => item.name}
/>
</SafeArea>
);
};
And then the component where the data hast to been show on the card:
export const SubCategoryScreen = () => {
const { subCategoryList } = useContext(CategoryContext);
return (
<SafeArea>
{console.log("test")}
<CategoryList
data={subCategoryList}
renderItem={({ item }) => {
console.log(item);
return (
<Spacer position="bottom" size="large">
<CategoryInfoCard category={item} />
</Spacer>
);
}}
keyExtractor={(item) => item.name}
/>
</SafeArea>
);
};
And this is the output from the api call:
GET /api/categories/2/
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"id": 2,
"name": "vogels",
"description": "vogels",
"legislation": "",
"review": "",
"eaza": "",
"images": "http://192.168.1.68:8000/media/photos/categories/birds.png",
"animals": [],
"subcategories": [
{
"id": 3,
"name": "roofvogels",
"description": "roofvogels",
"images": null
},
{
"id": 5,
"name": "parkieten",
"description": "parkieten",
"images": "http://192.168.1.68:8000/media/photos/categories/predator_gqLXVoK.jpg"
}
],
"category": null
}
ah, oke. I just figured something out.
So if I do this:
const retrieveSubCategories = () => {
setLoading(true);
setTimeout(() => {
fetchSubCategoryData()
//.then(subCategoryTransform)
.then((results) => {
setLoading(false);
setSubCategoryList([results]);
})
.catch((err) => {
setLoading(false);
setError(err);
});
});
};
with this:
export const SubCategoryScreen = () => {
const { subCategoryList } = useContext(CategoryContext);
return (
<SafeArea>
<CategoryList
data={subCategoryList}
renderItem={({ item }) => {
console.log("SUBCATEGORES", item.subcategories);
return (
<Spacer position="bottom" size="large">
<SubCategoryInfoCard subcategories={item.subcategories[0]} />
</Spacer>
);
}}
keyExtractor={(item) => item.name}
/>
</SafeArea>
);
};
Then I see the name and image of one card item: roofvogels.
But if I do this:
<SubCategoryInfoCard subcategories={item.subcategories} />
This doesn't work.
And the api call in the console.log is:
SUBCATEGORES Array [
Object {
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/predator_gqLXVoK.jpg",
"name": "parkieten",
},
]
So I try it like:
export const SubCategoryScreen = () => {
const { subCategoryList } = useContext(CategoryContext);
return (
<SafeArea>
<CategoryList
data={subCategoryList}
renderItem={({ item }) => {
console.log("SUBCATEGORES", item.subcategories);
return (
<Spacer position="bottom" size="large">
<Text>{item.subcategories} </Text>
</Spacer>
);
}}
keyExtractor={(item) => item.name}
/>
</SafeArea>
);
};
But then I get this error:
Error: Objects are not valid as a React child (found: object with keys {id, name, description, images}). If you meant to render a collection of children, use an array instead.
Question:How to return both of items: roofvogels and parkieten?
答案1
得分: 1
你没有实际调用发出 API 请求的函数。
useEffect(() => {}, [retrieveSubCategories]);
尝试:
useEffect(() => {
retrieveSubCategories();
}, []);
英文:
You're not actually calling the function which makes the api request.
useEffect(() => {}, [retrieveSubCategories]);
Try:
useEffect(() => {
retrieveSubCategories();
}, []);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论