gpt4 book ai didi

reactjs - 如何在 ReactJS 中链接 Action ?

转载 作者:行者123 更新时间:2023-12-04 13:34:56 26 4
gpt4 key购买 nike

如何将操作链接到 获取网址 图像属性 当我获取帖子列表时。
我提出了一个获取所有帖子的请求,它给了我一个属性“图像”的链接。
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,现在缺少的是 第二个请求 获取图像然后返回网址,以便我可以直接访问每个帖子的图像
简单的解决方案是使用 normalization_context 组
我正在使用 symfony api 平台,但它仍然为我提供了图像属性的链接,我认为是因为它是多对多关系

最佳答案

似乎不需要标准化。图像和评论特定于食谱。
通过 recipes 将 then 块回调设为异步有趣并在 then 块内循环首先数组,然后通过 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 的数据进行归一化处理因为许多食谱将使用相同的类别。在这种情况下,您将不得不重新构建 reducer 。

关于reactjs - 如何在 ReactJS 中链接 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62767519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com