2017-02-22 22 views
0

嗨,我希望這是一個語法的事情... 我有一個搜索框,它將它的值傳遞給一個reducer,我想用它來過濾一些數據並返回作爲一個新的狀態,但只有數組中包含搜索值的城市。Redux過濾器數組返回新狀態

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" 
}] 
+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 }); 

如果您使用巴貝爾在您預設啓用object spreadstage-3)和shorthand propertieses2015),你可一個這更簡潔:

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

    return { ...state, filteredLocations }; 
+0

我一直在想這個錯誤的方式。相反,或者試圖返回一個更新後的過濾函數,我已經將過濾移到了需要它的組件上。因此原始數據保持完整。 – Paulie