How to generate filtered list using reselect redux based on static filtered values?

跟風遠走 提交于 2021-02-11 06:08:34

问题


I am fetching news data from an API, in the app I need to show 3 lists. today news, yesterday news, article news.

I think I should use redux reselect. However, all the examples I am visiting has a dynamic filter value (state filter) while I need data to be fileted statically (no state changes these filters)

my state at the moment is

{news : [] }

How can I generate something like below using reselect

{news: [], todayNews:[], yesterdayNews:[], articleNews: []}

should I use reselect or I should just filter inside a component? I think reselect is memorized so I prefer to use reselect for performance


回答1:


You can do something like the following:

const { createSelector } = Reselect;
const state = {
  news: [
    { id: 1, name: 'one' },
    { id: 2, name: 'two' },
    { id: 3, name: 'three' },
  ],
};
const selectNews = (state) => state.news;
const selectOdds = createSelector(selectNews, (news) =>
  news.filter(({ id }) => id % 2 !== 0)
);
const selectEvens = createSelector(selectNews, (news) =>
  news.filter(({ id }) => id % 2 === 0)
);
const selectFilteredNews = createSelector(
  selectNews,
  selectEvens,
  selectOdds,
  (news, even, odd) => ({ news, even, odd })
);
const news = selectFilteredNews(state);
console.log('news:', JSON.stringify(news, undefined, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>


<div id="root"></div>

You use selectors when you need to calculate values based on state such as the total of a list or filtered things from a list. This way you don't need to duplicate the data in your state.



来源:https://stackoverflow.com/questions/62034927/how-to-generate-filtered-list-using-reselect-redux-based-on-static-filtered-valu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!