我使用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
它将显示所有列表,所以现在我不知道的是,当用户输入一些内容时,如何在列表中包含我筛选的数据,当文本框为空时,如何在列表中包含我的所有数据。
我希望这次解释得够清楚。