如何链行动,以获得url的图像属性,当我取帖子列表。
我已经提出了一个获取所有帖子的请求,它为我提供了属性“ image”的链接。
mywebsite / api / recipes?_page = 1:
{
"@context": "/api/contexts/Recipes",
"@id": "/api/recipes",
"@type": "hydra:Collection",
"hydra:member": [
{
"@id": "/api/recipes/524",
"@type": "Recipes",
"id": 524,
"category": "/api/categories/11",
"title": "NewPost",
"content": "This is a new post",
"time": "50 minutes",
"image": [
"/api/images/37"
],
"slug": "new-post",
"createdAt": "2020-06-30T10:26:00+00:00",
"comments": [
"/api/comments/1359",
"/api/comments/1360"
]
},
........
并且mywebsite / api / images / 37的结果是:
{
"url": "/images/5efbe9a4a1404818118677.jpg"
}
现在在我的行动中
export const recipesListError = (error) => ({
type: RECIPES_LIST_ERROR,
error
});
export const recipesListReceived = (data) => ({
type: RECIPES_LIST_RECEIVED,
data
});
export const recipesListFetch = (page = 1) => {
return (dispatch) => {
dispatch(recipesListRequest());
return requests.get(`/recipes?_page=${page}`)
.then(response => dispatch(recipesListReceived(response)))
.catch(error => dispatch(recipesListError(error)));
}
};
所以第一个请求是recipesListFetch,现在缺少的是第二个获取图像的请求,然后返回url,这样我就可以直接访问每个帖子的图像
如果我正在使用symfony api平台,最简单的解决方案是使用normalization_context组,但是它仍然为我提供了image属性的链接,我认为这是因为ManyToMany关系
似乎没有必要进行标准化。图像和注释特定于配方。
使then块回调作为异步乐趣,然后在内部进行块循环recipes
,然后先通过image
数组循环,然后再通过数组循环,并对图像进行api调用并等待它。
export const recipesListFetch = (page = 1) => {
return (dispatch) => {
dispatch(recipesListRequest());
return requests
.get(`/recipes?_page=${page}`)
.then(async (response) => {
//make then callback as async fun
const recipes = response["hydra:member"];
const imagesForTheRecipie = [];
for (let i = 0; i < recipes.length; i++) {//loop thru recipies
for (let j = 0; j < recipes[i].image.length; j++) {//loop thru images for each recipie
const imageUrl = recipes[i].image[j];//grab the image url
const image = await requests.get(`/${imageUrl}}`);
imagesForTheRecipie.push(image);
}
recipes[i].image = imagesForTheRecipie; //mutate the object which will directly update the response
}
dispatch(recipesListReceived(response));
})
.catch((error) => dispatch(recipesListError(error)));
};
};
注意-如果需要,normalise
则可以选择将数据标准化,categories
因为许多食谱将使用同一类别。在这种情况下,您将必须重新构造减速器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句