我有以下代码按搜索栏上的名称进行过滤。
state = {
canchas,
canchasFiltradas: [],
}
componentDidMount () {
this.setState({canchasFiltradas: this.state.canchas})
}
buscarCanchas = (name) => {
this.setState({
canchasFiltradas: this.state.canchas.filter(cancha => {
return cancha.name.indexOf(name) > -1
})
})
}
canchas在哪里引用json文件。这是搜索栏组件:
<SearchBar
onChangeText={nombre => this.buscarCanchas(nombre)}
onClearText={() => this.setState({canchas})}
/>
现在,我将redux添加到项目中,但它不起作用。 这是化简代码:
const initialState = {
canchas,
canchasFiltradas: [],
};
const reducer = (state=initialState, action) => {
switch (action.type) {
case BUSCAR_CANCHA:
return {
...state,
canchas: state.canchas.filter(cancha => {
return cancha.name.indexOf(action.name) > -1
})
};
default:
return state;
}
};
答案 0 :(得分:0)
您正在覆盖化简器中的原始状态值。这就是为什么当您清除搜索时它不会显示所有内容。您应该将过滤后的数据存储在canchasFiltradas
中,而不是canchas
中。
参见下文:
const initialState = {
canchas,
canchasFiltradas: [],
};
const reducer = (state=initialState, action) => {
switch (action.type) {
case BUSCAR_CANCHA:
return {
...state,
canchasFiltradas: state.canchas.filter(cancha => {
return cancha.name.indexOf(action.name) > -1
})
};
default:
return state;
}
};