Reactjs 如何将componentDidMound和componentWillUnmount与Firebase/Firestore一起转换为UseEffect(反应挂钩)?
在使用Firebase时,如何使用useEffect钩子替换componentDidMount和componentWillUnmount?我找不到此“取消订阅”功能的解决方案Reactjs 如何将componentDidMound和componentWillUnmount与Firebase/Firestore一起转换为UseEffect(反应挂钩)?,reactjs,firebase,Reactjs,Firebase,在使用Firebase时,如何使用useEffect钩子替换componentDidMount和componentWillUnmount?我找不到此“取消订阅”功能的解决方案 unsubscribe = null; componentDidMount = async () => { this.unsubscribe = firestore.collection('posts').onSnapshot(snapshot => { const posts = snapsho
unsubscribe = null;
componentDidMount = async () => {
this.unsubscribe = firestore.collection('posts').onSnapshot(snapshot => {
const posts = snapshot.docs.map(...)
this.setState({ posts })
})
}
componentWillUnmount = () => {
this.unsubscribe()
}
useEffect(() => {
let unsubscribe;
async function getSnapshot() {
unsubscribe = firestore.collection('posts').onSnapshot((snapshot) => {
const posts = snapshot.docs.map(...)
setPosts(posts);
});
}
getSnapshot();
return () => {
unsubscribe();
};
}, []);
以下是我尝试过的:
useEffect(() => {
async function getSnapshot() {
const unsubscribe = firestore.collection('posts').onSnapshot(snapshot => {
const posts = snapshot.docs.map(...)
setPosts(posts)
}
getSnapshot()
//return something to clear it? I don't have access to 'unsubscribe'
}, [])
您可能会在useEffect内部使用async时遇到问题,请检查 编辑:实际上,从文档中可以看出,您根本不需要异步: 你试过这种格式吗
useEffect(
() => {
const unsubscribe = firebase
.firestore()
.collection('recipes')
.doc(id)
.collection('ingredients')
.onSnapshot( snapshot => { const ingredients = [] snapshot.forEach(doc => { ingredients.push(doc) }) setLoading(false) setIngredients(ingredients) }, err => { setError(err) } )
return () => unsubscribe()
},
[id]
)
事实上,你的答案很接近。您没有在函数中使用wait,因此使用它没有任何意义
useEffect(() => {
const unsubscribe = firestore.collection('posts').onSnapshot((snapshot) => {
const posts = snapshot.docs.map(...)
setPosts(posts);
});
return () => {
unsubscribe();
};
}, []);
如果确实需要使用async,则可以利用闭包来取消订阅async函数
unsubscribe = null;
componentDidMount = async () => {
this.unsubscribe = firestore.collection('posts').onSnapshot(snapshot => {
const posts = snapshot.docs.map(...)
this.setState({ posts })
})
}
componentWillUnmount = () => {
this.unsubscribe()
}
useEffect(() => {
let unsubscribe;
async function getSnapshot() {
unsubscribe = firestore.collection('posts').onSnapshot((snapshot) => {
const posts = snapshot.docs.map(...)
setPosts(posts);
});
}
getSnapshot();
return () => {
unsubscribe();
};
}, []);