如何在redux store redux中清除搜索过滤功能后返回原始状态 [英] How to return the original state after a search filter function has been cleared in redux store redux
问题描述
我有一个搜索和过滤功能,我想实现它,用户将搜索项目,它们将在平面列表中返回,当用户清除搜索框或搜索框为空时,我希望初始状态为被退回.
I have a search and filter function which I want to implement whereby a user will search for items and they will be returned in a flatlist and when the user clears the search box or the search box is empty I want the initial state to be returned.
我试过这个:该功能确实过滤了商店,但是当我清除它时,原始状态项目不再存在.返回的是搜索值
I've tried this: The function does filter through the store but when I clear it, the original state items are no longer there. What is returned are the search values
search: (state, { payload }) => {
const itemsToFilter = state.filter((item) => {
let itemLowerCase = item.item_description.toLowerCase();
let searchItemToLowerCase = payload.item_description.toLowerCase();
return itemLowerCase.indexOf(searchItemToLowerCase) > -1;
});
if (payload.item_description.length !== 0) {
return itemsToFilter;
} else {
return state;
}
},
这是我的组件函数
import {useDispatch, useSelector} from 'react-redux';
const [searchValue, setSearchValue] = useState("");
const items = useSelector(state => state.items)
const dispatch = useDispatch()
const searchItems = (e) => {
const text = e.nativeEvent.text;
setSearchValue(text);
dispatch(
searchItemAction({
item_description: searchValue,
})
);
};
<TextInput value={searchValue} onChange={searchItems} />
推荐答案
首先,useState()
是异步的,因此您的调度使用的是旧字符串.
first of all, useState()
is async so your dispatch is using the old string.
const searchItems = (e) => {
const text = e.nativeEvent.text;
setSearchValue(text); // Will be updated async
dispatch(
searchItemAction({
item_description: searchValue, //searchValue will still be the old search value
})
);
};
简单的解决方案是使用 text
变量:
easy solution would be to use the text
variable:
const searchItems = (e) => {
const text = e.nativeEvent.text;
setSearchValue(text);
dispatch(
searchItemAction({
item_description: text,
})
);
};
另外,您将原始数据存储在哪里?你应该创建一个选择器,这样就可以了.
also, where do you store your orignal data? you should create a selector instead and it would be fine.
我认为最好的解决方案是仅在此组件中使用选择器(如果您在其他任何地方都不需要它):
i think the best solution would be to use the selector only in this component (if you don't need it anywhere else):
const [searchValue, setSearchValue] = useState("");
const items = useSelector(state => {
if(searchValue.length === 0) {
return state.items;
}
return state.items.filter((item) => {
let itemLowerCase = item.item_description.toLowerCase();
let searchItemToLowerCase = searchValue.toLowerCase();
return itemLowerCase.indexOf(searchItemToLowerCase) > -1;
});
}
const searchItems = (e) => {
const text = e.nativeEvent.text;
setSearchValue(text);
};
否则您需要将搜索字符串存储到 redux 并使用存储的字符串在选择器中进行过滤.
otherwise you will need to store the search string to redux and use the stored string to do the filter in the selector.
这篇关于如何在redux store redux中清除搜索过滤功能后返回原始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!