代码之家  ›  专栏  ›  技术社区  ›  Emad Dehnavi

用Redux反应native |如何过滤数据并将初始数据保持在reudx状态

  •  0
  • Emad Dehnavi  · 技术社区  · 7 年前

    我使用React Native&Redux为我的移动应用程序实现了一个简单的搜索功能,我从API获取数据并将它们保存在我的Redux商店中,所以当应用程序运行时,我已经有了一个项目列表。

    以下是我的行动:

    import { GET_CRYPTO_DATA, FILTER_CRYPTO_DATA } from './types';
    
    export function GetCryptoData(data){
      return {
        type: GET_CRYPTO_DATA,
        payload: data
      }
    }
    
    export function FilterCryptoData(filteredData) {
      return {
        type: FILTER_CRYPTO_DATA,
        payload: filteredData
      }
    }
    

    所以第一个会有所有的数据,第二个会有 filteredData

    这是我的减速机:

    import { GET_CRYPTO_DATA, FILTER_CRYPTO_DATA } from '../actions/types';
    
    export default function(state= {}, action){
      switch (action.type){
        case GET_CRYPTO_DATA:
            return [...state, action.payload]
        case FILTER_CRYPTO_DATA:
            return [...state, action.payload]
        default:
            return state;
      }
    }
    

    import { combineReducers } from 'redux';
    
    import CryptoDataReducer from './CryptoDataReducer';
    
    export default combineReducers({
        cryptoData : CryptoDataReducer
    })
    

    更新

    让我与您分享我的子组件可能会更清楚,因此这是我在父组件中呈现的内容:

    render() {
    return (
        <View style={styles.container}>
          <HeaderComponent />
          <SearchComponent search={this.handleSearch} />
          <CryptoListComponent myList={this.props.cryptoData}/>
    
        </View>
    );
    }
    

    <SearchComponent search={this.handleSearch} /> 组件,它有一个文本框和一个按钮,这个组件所做的只是将用户输入的用于筛选数据的关键字传递给我。在我的 this.handleSearch 我会像这样过滤数据:

    let filteredData = []
    handleSearch = (keyword) => {
      let result = []
      if(keyword===''){
        filteredData = this.props.cryptoData
      } else {
        this.props.cryptoData.map(item => {
            if (item.name.toLowerCase().startsWith(keyword.toLowerCase())) {
                result.push(item)
            }
        })
        filteredData = result
      }
    }
    

    所以我有 过滤数据 现在,我试着把这个作为道具传给我的 CryptoListComponent 组件,但是我总是得到空列表,但是当我通过redux商店道具时 this.props.cryptoData 它将显示所有列表,所以现在我不知道的是,当用户输入一些内容时,如何在列表中包含我筛选的数据,当文本框为空时,如何在列表中包含我的所有数据。

    我希望这次解释得够清楚。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Emad Dehnavi    7 年前

    我知道Redux状态是唯一的真相来源,但是我认为在这种情况下,我们还需要一个组件级的状态,它只对我们的父组件可见,所以多亏了这个 article 我向父组件添加了一个组件状态,如下所示:

     state = {
        currentlyDisplay : []
     }
    

    基于用户输入,我将更新此状态,因此如果搜索框为空,我将用Redux应用程序级状态(使用mapstatetops映射)更新它,如果用户尝试筛选,我将使用筛选的数据更新它,因此在这种情况下,我可以通过 currentlyDisplay 到将呈现列表的子组件。这种方法给了我我需要的,我分享这个,以防有人需要。如果有更好的方法达到同样的效果,请告诉我,我很乐意学习。