Redux:在reducer中过滤数据数组的正确方法是什么?
我想在搜索上过滤一个数组SEARCH_TEXT是一个改变动作
我很困惑的是当按下删除键并且文本现在变空时我如何返回状态,我想我可以在else语句中使用初始状态但我倾向于这是错误的?当我返回状态时,它已经在if语句中被操作了。
i want to filter an array on search SEARCH_TEXT is an on change action what I'm confused with is how i return the state when the delete key is pressed and the text now becomes empty, i figure i could use initial state in the else statement but my inclination is this is wrong? when i return just state it has all ready been manipulated in the if statement.
简单示例。
谢谢提前。
const initialState = ['hello', 'wahhh', 'yo'];
export default function searchSimple(state = initialState, action) {
switch (action.type) {
case SEARCH_TEXT:
if(action.text.length > 0){
return state.filter(item =>
item.startsWith(action.text)
)
}
else {
return state
}
永远记得国家是你的真理之源。警惕在临时过滤器的基础上消除状态。一旦你这样做,这些项目就不见了。 (让他们回来的唯一方法是将你的状态重置为initialState,这可能不太理想。)
Remember always that the state is your "source of truth". Be wary of eliminating state on the basis of a temporary filter. Once you do so those items are gone. (The only way to get them back is to reset your state to the initialState, which may not be ideal.)
更好的办法是保持你的物品清单不变,只需存储搜索文本。
A better approach is to keep your items list as is, and simply store the search text.
const initialState = {
searchText: '',
items: [ 'hello', 'wahhh', 'yo' ]
};
export default function searchSimple(state = initialState, action) {
switch (action.type) {
case SEARCH_TEXT:
return Object.assign({}, state, {
searchText: action.text
});
}
}
虽然您的州不包含已过滤的列表,它告诉你构建过滤列表需要知道的一切。
Whilst your state won't contain the filtered list, it tells you everything you need to know to construct the filtered list.
假设您正在使用React,您的智能组件可以使用以下 mapStateToProps() function:
Assuming you're using React, your "smart component" can be setup with the following mapStateToProps()
function:
function mapStateToProps(state) {
const { items, searchText } = state.searchSimple;
return {
filteredItems: items.filter((item) => item.startsWith(searchText))
};
}
如果您需要在多个地方使用此过滤列表,请考虑创建选择器功能,如Redux购物车示例中所示。
https:// github .com / reactjs / redux / blob / master / examples / shopping-cart / src / reducers / cart.js
Should you need this filtered list in more than one place, consider creating a "selector" function, as demonstrated in the Redux shopping cart example. https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/cart.js
它看起来像这样:
export function filteredItems(state) {
const { items, searchText } = state.searchSimple;
return items.filter((item) => item.startsWith(searchText));
}
有关选择器的更高级方法,请查看重新选择库。
For a more advanced approach to selectors, check out the reselect library.