首页 > 解决方案 > 在 reducer 中更新搜索功能的状态

问题描述

我正在尝试创建一个搜索功能来更新商店中的状态,但是一旦我停止搜索,reducer 实际上会向状态广告过滤结果。所以我最终重复了。

当搜索输入为空时,我分派初始提取,但过滤后的结果被添加到状态中。

这是我的减速机

    switch(action.type){
        case GET_ENTRIES:
            return [ ...state, ...action.entries ]   
        case SEARCH_ENTRIES:      
            return [...action.entries]
         default:        
             return state
    }

我的行动

export const searchHandle = (query) => (dispatch, getState) => {
    const theState = getState()    
    const entries = theState.entriesData.filter(val => (
        val.firstName.includes(query) ||
        val.lastName.includes(query)  ||
        val.phoneNumber.includes(query)
    ))    
    dispatch({ 
        type:SEARCH_ENTRIES, 
        entries
    })        
}

和处理程序

const handleChange = (e) => {
        e.target.value.length > 0 ? dispatch(searchHandle(e.target.value))
        : dispatch(entriesCall())
    }

标签: javascriptarraysreactjs

解决方案


推荐阅读