0

我正在玩一个简单的应用程序,它显示来自 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>
);
 };
4

1 回答 1

0

我想到了。在调用调度之前,我需要在 AddPost 中写入数据库。就这样。

于 2020-08-02T01:10:55.547 回答