Redux过滤器数组返回新状态

时间:2017-02-22 17:54:47

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

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

  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"
}]

1 个答案:

答案 0 :(得分: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 spreadstage-3)和shorthand propertieses2015),则可以使其更加简洁:

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

  return { ...state, filteredLocations };