2016-08-17 28 views
0

我有一個問題試圖在我的應用程序中創建「typehead」函數,我有一個「輸入」來監聽onChange,並且onChange正在調用Redux減速器,在洞商店搜索標籤,我需要搜索所有匹配與我的搜索,在這裏一切都很好,但是當我刪除我的搜索,我的洞商店等於我的篩選結果,我希望當我的搜索是空的它返回我的商店洞。 (gif等代碼)如何在返回所有商店時篩選出反應js和redux

enter image description here

case 'SEARCH_BY_TAG': 
      let tag = action.tag 
      let filtered = state.slice(0) 
      if(tag != ""){ 

       const copied = state.filter(item => { 
         return item.tags.find(obj => { 
          if(obj.name.indexOf(tag) > -1){ 
           return true 
          } 
         }) 
       }) 

       return filtered = copied.filter(Boolean) 

      }else{ 
       return filtered 
      } 

break; 

回答

1

我想你應該重構你的狀態,從這個改變:

[ item1, item2, item3, ... ] 

這樣:

{ 
    query: '', 
    options: [ item1, item2, item3, ... ] 
} 

這樣你就可以做什麼@Raspo他回答說 - 做濾波渲染函數中的選項。

目前,當您更改搜索字段中的文本,你分派此動作:

{ 類型:「SEARCH_BY_TAG」, 標籤:「新查詢」 }

我想你應該改變動作名稱,和減速器代碼,看起來更像是這樣的:

// note this is almost exactly the same as the old action 
{ 
    type: 'CHANGE_AUTOCOMPLETE_QUERY', 
    query: 'new query' 
} 

,然後減速可以改成這樣:

case CHANGE_AUTOCOMPLETE_QUERY: 
    return Object.assign({}, state, { 
    query: action.query 
    }) 

請注意,在剛纔寫的減速器情況下,狀態的options部分根本沒有改變。它保持不變。

現在讓我們假設你目前的渲染功能看起來是這樣的:

const options = reduxState // not sure exactly how you get the state but whatever 
return (
    <div> 
    {options.map(option => { 
     <Option option={option} /> 
    })} 
    </div> 
) 

此代碼依賴於獲得國家作爲一個數組。您可以在新設置中更改它以執行此操作:

const query = reduxState.query 
const options = reduxState.options.filter(item => { 
    return item.tags.find(obj => { 
    if(obj.name.indexOf(query) > -1){ 
     return true 
    } 
    }) 
}) 
return (
    <div> 
    {options.map(option => { 
     <Option option={option} /> 
    })} 
    </div> 
) 
2

而不是過濾東西拿出來,機內部,直接做在render(),沒有什麼不妥。

您仍然可以使用SEARCH_BY_TAG操作來跟蹤搜索關鍵字,並使用它來在呈現列表時應用過濾器。