问题
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