javascript - React - 有条件地更新减速器内的状态
问题描述
介绍
我有一个 React Context Provider,它有一个有状态的“帖子”数组。
我的想法是提供 3 种方法,一种用于添加,另一种用于更新,最后一种用于删除。
因此,如果用户从数据库中获取 10 个帖子,则必须将它们保存在上下文提供程序中:
const newPosts = await fetchPosts(cursor, startAfter, limit);
// Save the new posts in the Posts Context
contents.addContents(newPosts);
但是,如果其中一个帖子已经保存了怎么办?我需要忽略已经添加的帖子。
问题
这是我的内容上下文:
export function ContentsProvider({ children }) {
const [contents, dispatch] = useReducer(contentsReducer, new Map([]));
const addContents = (newContents) => {
dispatch({
type: "add-contents",
newContents,
});
}
...
return (
<ContentsContext.Provider
value={{
addContents,
...
}}
>
{children}
</ContentsContext.Provider>
)
}
如何避免添加已保存的内容?我的意思是,在方法 addContents 方法中还是在我的 reducer 中是正确的方法吗?
const contentsReducer = (contents, action) => {
switch (action.type) {
case "add-contents": {
const { newContents } = action;
return new Map([...contents, ...newContents]);
}
...
};
我问是因为有条件地更新减速器内部的状态对我来说似乎很奇怪,也许它是一种反模式。
有任何想法吗?
这是我目前的解决方案:
export default (contents, action) => {
switch (action.type) {
case "add-contents": {
let { newContents } = action;
// Avoid storing already added contents
newContents = newContents.filter(
(newContent) => !contents.get(newContent.id)
);
if (!newContents.length) return contents;
return new Map([...contents, ...newContents]);
}
...