如何在 ReactJS 中链接动作?

How to chain actions in ReactJS?

当我获取 post列表。

我提出了一个获取所有 post 的请求,它为我提供了 属性“图片”的 link。

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,现在缺少的是第二个请求获取图像,然后return url 这样我就可以直接访问每个 post

的图像

简单的解决方案是使用 normalization_context 组 我正在使用 symfony api 平台,但它仍然为图像 属性 提供 link,我想是因为它是多对多关系

好像没有规范化的必要。图片和评论特定于食谱。

将 then 块回调设置为异步有趣,并在 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 的数据进行归一化处理,因为同一类别将被许多食谱使用.在那种情况下,您将不得不重新构造您的减速器。