reactjs - 删除组件卸载文档(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()
}
但是,这不起作用。有谁知道为什么?
解决方案
问题
它不起作用,因为您似乎关闭了初始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
};
}, []);
推荐阅读
- javascript - Nativescript - Filterselect,RadListView。我用哪一个?
- python - 蓝牙:bluetooth_adapter_winrt.cc 获取默认适配器失败
- java - 如何拦截 Hotspot JVM 中的内存访问/更改?
- rust - 如何在 rust 中返回链式迭代器
- redis - list-max-ziplist-entries 和 list-max-ziplist-value 的值会有多大影响性能
- c# - 将值从文本框传递到 datagridview
- marklogic - MarkLogic DHF 5.2.1 快速入门 - 本地设置 - 未找到流
- excel - 从不同的工作簿中搜索
- django - 无法使用 Django 使用 Youtube API 上传视频(设置 GOOGLE_APPLICATION_CREDENTIALS 错误)
- javascript - Typescript 解析模型响应的最佳方法