【问题标题】:Delete doc on component unmount (React and Firebase)删除组件卸载文档(React 和 Firebase)
【发布时间】:2021-08-29 07:31:05
【问题描述】:

我有一个反应组件,它将在安装时创建一个新文档

const CreateGame: React.FunctionComponent<ICreateGameProps> = (props) => {


    const gamesRef = useFirestore()
        .collection('Games')

    const [newGameId, setNewGameId] = useState('')

    useEffect(() => {
        const newGame: IGameDoc = {
            playerTurn: 'x',
            secondPlayerJoined: false,
            gameState: {
                rowOne: [null, null, null],
                rowTwo: [null, null, null],
                rowThree: [null, null, null]
            }
        }

        gamesRef.add(newGame)
            .then(docRef => setNewGameId(docRef.id))

        return () => {
            gamesRef.doc(newGameId).delete()
        }

    }, [])

但是,一旦组件再次卸载,我想再次删除同一个文档,因此我的 useEffect 挂钩中有清理功能

return () => {
    gamesRef.doc(newGameId).delete()
}

但这不起作用。有谁知道为什么?

【问题讨论】:

    标签: reactjs firebase react-hooks use-effect


    【解决方案1】:

    问题

    它不起作用,因为您似乎关闭了初始 newGameId 状态,该状态的值为 '',而不是它更新为的 docRef.id

    解决方案

    使用额外的useRef 挂钩缓存newGameId 状态值的副本,并在useEffect 挂钩的清理函数中引用它。

    const gameIdRef = useRef(); // <-- create a ref to store game id
    const gamesRef = useFirestore().collection('Games');
    
    const [newGameId, setNewGameId] = useState('');
    
    useEffect(() => {
      const newGame: IGameDoc = {
        playerTurn: 'x',
        secondPlayerJoined: false,
        gameState: {
          rowOne: [null, null, null],
          rowTwo: [null, null, null],
          rowThree: [null, null, null]
        }
      }
    
      gamesRef
        .add(newGame)
        .then(docRef => {
          setNewGameId(docRef.id);
          gameIdRef.current = docRef.id; // <-- cache game id
        })
    
      return () => {
        gamesRef.doc(gameIdRef.current).delete(); // <-- access ref's current value
      };
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2014-04-04
      • 2016-11-28
      相关资源
      最近更新 更多