我想在搜索上过滤一个数组SEARCH_TEXT是一个改变动作,我很困惑的是当按下删除键并且文本现在变为空时我如何返回状态,我想我可以在else语句中使用初始状态但我倾向于这是错的?当我返回状态时,它已经在if语句中被操作了.
简单的例子.
提前致谢.
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
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*lsh 85
永远记住,国家是你的"真理之源".警惕在临时过滤器的基础上消除状态.一旦你这样做,这些项目就不见了.(让它们恢复的唯一方法是将状态重置为initialState,这可能并不理想.)
更好的方法是保持项目列表不变,只需存储搜索文本.
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
});
}
}
Run Code Online (Sandbox Code Playgroud)
虽然您的州不会包含已过滤的列表,但它会告诉您构建过滤列表需要了解的所有信息.
假设您正在使用React,可以使用以下mapStateToProps()功能设置"智能组件" :
function mapStateToProps(state) {
const { items, searchText } = state.searchSimple;
return {
filteredItems: items.filter((item) => item.startsWith(searchText))
};
}
Run Code Online (Sandbox Code Playgroud)
如果您需要在多个位置使用此筛选列表,请考虑创建"选择器"功能,如Redux购物车示例中所示. 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));
}
Run Code Online (Sandbox Code Playgroud)
有关选择器的更高级方法,请查看重新选择库.
https://github.com/rackt/reselect
小智 19
IMO,过滤数据的正确位置不是直接在Reducer中,而是在选择器中.
来自redux docs:
Reselect是一个用于创建memoized,可组合选择器函数的简单库.重选选择器可用于有效地计算Redux存储中的派生数据.
我目前正在使用选择器来过滤和排序数据.
| 归档时间: |
|
| 查看次数: |
42081 次 |
| 最近记录: |