【问题标题】:Redux filter array return new stateRedux 过滤器数组返回新状态
【发布时间】:2017-07-12 22:32:42
【问题描述】:

嗨,我希望这是一个语法问题... 我有一个搜索框,它将它的值传递给一个减速器,我想用它来过滤一些数据并作为新状态返回,但只有数组中包含搜索值的城市。

  case 'FILTER_LOCATIONS' :
    const data = action.serverData
      .filter(cityName => {
        return cityName.city.toLowerCase().indexOf(action.event) >= 0
      });
      console.log(data);

    return state;

数据返回过滤后的数组,但我如何更新我的状态?

**更新

抱歉,有点菜鸟。

serverData 位于树的根部,看起来有点像这样:

serverData [{
  "id": 1,
  "full_name": "Eric Myers",
  "city": "Sydney",
  "lat": "-33.8678",
  "lng": "151.2073",
  "country": "Australia"
}, {
  "id": 2,
  "full_name": "Ruth Torres",
  "city": "Simpang",
  "lat": "-7.1406",
  "lng": "107.0033",
  "country": "Indonesia"
}, {
  "id": 3,
  "full_name": "Kevin Collins",
  "city": "Herrljunga",
  "lat": "58.0774",
  "lng": "13.0266",
  "country": "Sweden"
}]

【问题讨论】:

  • 生成的数组在你的状态下到哪里去了?请编辑您的问题以包含您的状态树的简要说明/示例。

标签: arrays ecmascript-6 redux filtering react-redux


【解决方案1】:

您还没有告诉我们这些数据应该在您的状态树中的哪个位置,但是假设您要设置一个名为 filteredLocations 的属性,您可以这样做:

case 'FILTER_LOCATIONS' :
  const data = action.serverData
    .filter(cityName => cityName.city.toLowerCase().indexOf(action.event) >= 0);

  return Object.assign({}, state, { filteredLocations: data });

如果你使用 Babel 并且在你的预设中启用了 object spread (stage-3) 和 shorthand properties (es2015),你可以让它更简洁:

case 'FILTER_LOCATIONS' :
  const filteredLocations = action.serverData
    .filter(cityName => cityName.city.toLowerCase().indexOf(action.event) >= 0);

  return { ...state, filteredLocations };

【讨论】:

  • 我做错了。相反,或者尝试返回更新的过滤函数,我已将过滤移至需要它的组件。因此原始数据保持不变。
猜你喜欢
  • 2017-03-26
  • 1970-01-01
  • 2021-10-09
  • 2020-10-22
  • 2018-09-28
  • 2016-11-20
  • 1970-01-01
  • 2020-12-01
  • 2017-12-08
相关资源
最近更新 更多