如何在React Native Redux-Reducer

时间:2019-01-31 13:29:43

标签: reactjs react-native redux react-redux

我有一个名为fetchProperties的操作,用于获取所有列表和与数据相关的所有数据。响应看起来像这样,我正在为Redux存储设置此信息(20个列表)。

{
  "status":"success",
  "listings":[
             {
               "id": "1",
               "streetnum": "370",
               "streetname": "Pack Saddle Drive",
               "city": "Horseshoe Bay",
               "area": "Blue Lake Estates",
               "zipcode": "78657",
             },
             {...}
             // 20 out of 300 properties
             ],
  "total_found":300,
  "some_other" : "some other data"
}

在下一次调用中提取接下来的20个列表时,API返回与上述相同的结构,但是我想将新的listings数组追加到Redux存储中的旧listings数组。 / p>

对于这种情况,如何编写减速器?我尝试如下所示,但没有成功,

    export default function propertiesList(state = { listings: [] }, action) {
  switch (action.type) {
    case FETCH_PROPERTIES:
      // return action.payload.body;
      return {
        ...state,
        listings: [...state.listings, ...action.payload.body]
      };
}

,最终状态应为:

{
  "status":"success",
  "listings":[
             {
               "id": "1",
               "streetnum": "370",
               "streetname": "Pack Saddle Drive",
               "city": "Horseshoe Bay",
               "area": "Blue Lake Estates",
               "zipcode": "78657",
             },
             {...}
             // 40 out of 300 properties
             ],
  "total_found":300,
  "some_other" : "some other data"
}

2 个答案:

答案 0 :(得分:1)

在reducer成功的情况下,您只需要在清单上附加旧清单即可,例如:

case FETCH_PROPERTIES:
  return { 
    ...state, 
    listings: [
      ...state.listings,
      ...action.payload.body,
    ]
  }

假设FETCH_PROPERTIES是您的成功案例

答案 1 :(得分:0)

我已将减速器更改为这样。

public DownloadStringResult DownloadString(string url)
{
    DownloadStringResult result = new DownloadStringResult();
    try
    {
        var html = base.GetStringAsync(url).Result; // base is HttpClient.
        if (html.Contains(WebSiteDto.LogoutMessage) || html.Contains("Please Login")) // Log-out website. So I need to re-login again.
        {
            result.IsRelogged = true;
            result.HtmlResult = GetLoginResult(); // re-login
            return result;
        }
        result.HtmlResult = html;
    }
    catch (Exception e) // This try catch for TimeOut Exception. I try many way but I still cant catch timeout exception. Or I cant tell wait just 5 second, if no answer then retry again.
    {
        return DownloadString(url);
    }

    return result;
}

并且在第一次调用export default function propertiesList(state = { listings: [] }, action) { switch (action.type) { case FETCH_PROPERTIES: return { ...action.payload.body, listings: [...state.listings, ...action.payload.body.listings] }; case EMPTY_PROPERTIES_STORE: return { listings: [] }; } 之前,我调用了操作fetchProperties,以确保我的空存储中包含空的EMPTY_PROPERTIES_STORE数组