首页 > 解决方案 > 删除组件卸载文档(React 和 Firebase)

问题描述

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

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()
}

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

标签: reactjsfirebasereact-hooksuse-effect

解决方案


问题

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

解决方案

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

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
  };
}, []);

推荐阅读