我有一个使用Redux进行状态管理的react js应用程序。它具有显示在屏幕上的消息列表。还有两个下拉菜单,可根据产品消息和订单消息过滤列表。整个消息列表来自redux状态。
我尝试执行此操作,但是遇到一个问题,一旦我下次过滤列表,它将尝试从过滤的列表中运行过滤器,结果是那里没有消息。
我不确定这是否是正确的方法。
reducers.js
const initialState = {
loading: false,
loaded: false,
messageList: [], <---- I am displaying this messageList in my component.
fetchError: null,
}
export default (state=initialState, action) => {
switch (action.type) {
case GET_MESSAGE_LIST_LOAD:
return {
...state,
loading: true
};
case GET_MESSAGE_LIST_SUCCESS:
return {
...state,
loading: false,
loaded: true,
messageList: action.payload,
};
case FILTER_MESSAGE_BY_ORDER:
return {
...state,
filterState: action.payload,
messageList: state.messageList.filter((item)=> {
return item.productId === null;
})
};
case FILTER_MESSAGE_BY_PRODUCT:
return {
...state,
filterState: action.payload,
messageList: state.messageList.filter((item) => {
return item.orderNumber === null;
})
};
case GET_MESSAGE_LIST_ERROR:
return {
...state,
loaded: false,
fetchError: action.error,
};
default:
return {
...state
};
}
}
action.js
export const getMessageList = () => dispatch => {
dispatch({
type: GET_MESSAGE_LIST_LOAD
});
new _rest().get('message/list')
.then(res => {
// console.log('messageList',res)
dispatch({
type: GET_MESSAGE_LIST_SUCCESS,
payload: res.data._embedded.messageListResourceList
})
}).catch(err => {
dispatch({
type: GET_MESSAGE_LIST_ERROR,
error: err
})
})
}
export const filterOrderMessage = () => dispatch => {
dispatch({
type: FILTER_MESSAGE_BY_ORDER
})
}
export const filterProductMessage = () => dispatch => {
dispatch({
type: FILTER_MESSAGE_BY_PRODUCT
})
}
这是我的UI外观
它的顶部具有下拉菜单,其中必须具有用于过滤
ORDER MESSAGE
和PRODUCT MESSAGE
的选项。最佳答案
您正在变异messageList。而是对存储中的已过滤邮件设置单独的状态。在您的组件中,确保基于filteredMessageList进行渲染。
代码样例
const initialState = {
loading: false,
loaded: false,
messageList: [],
filteredMessageList: [], // <----- create a new state
fetchError: null,
}
...
case FILTER_MESSAGE_BY_ORDER:
return {
...state,
filterState: action.payload,
filteredMessageList: state.messageList.filter((item)=> { // <----update filteredMessageList (not messageList)
return item.productId === null;
})
};
关于javascript - 如何在ReactJS中从相同的Redux状态进行两种类型的过滤,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61584375/