我正在玩一个简单的应用程序,它显示来自 firebase 的帖子集合并允许用户向其中添加文档。帖子通过包含 ADD 函数的 PostsContext 共享。useReducer 被调用两次,没有绕过它。问题是我正在从 ADD 内部写入 firebase,这会导致重复的行。
export const PostsContext = React.createContext();
export const PostsProvider = function ({ children }) {
const reducer = function (state, action) {
switch (action.type) {
case "ADD": {
const newPost = {
id: id(),
title: action.payload.title,
content: action.payload.comment,
};
console.log("THIS GETS CALLED TWICE");
firestore.collection("posts").add(newPost);
return [newPost, ...state];
}
case "INIT": {
console.log(action.payload);
return [...action.payload.posts];
}
}
return state;
};
const [posts, dispatch] = useReducer(reducer, []);
const addPost = function (title, comment) {
dispatch({
type: "ADD",
payload: {
title,
comment,
},
});
};
const initPosts = function (posts) {
dispatch({
type: "INIT",
payload: {
posts,
},
});
};
const value = { posts, addPost, initPosts };
return (
<PostsContext.Provider value={value}>{children}</PostsContext.Provider>
);
};