【问题标题】:Writing to firebase from dispatch results in duplicate rows从调度写入firebase会导致重复的行
【发布时间】:2020-08-01 22:07:25
【问题描述】:

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

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore dispatch use-reducer


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多