React Native Firestore 无限循环

React Native Firestore infinite loop

我正在尝试使用 documentSnapshot 从 firestore 获取用户数据,我可以获取数据,但它陷入无限循环,正在更新用户数据,

这是代码

import firestore from '@react-native-firebase/firestore';
export default function HomeScreen() {
     const { user, logout } = useContext(AuthContext);
     const [currentUser, setCurrentUser] = useState('');

     useEffect(() => {
      firestore()
           .collection('users')
           .doc(user.uid)
           .get()
           .then(documentSnapshot => {
                if (documentSnapshot.exists) {
                     setCurrentUser(documentSnapshot.data())
                }
           })

 })
 return (
      <View style={styles.container}>
           <Title>{currentUser.displayName}</Title>
           <FormButton
                modeValue='contained'
                title='Logout'
                onPress={() => logout()} />
      </View>
 )
}

每次调用 setCurrentUser 时都会强制重新渲染(因为这是一个状态变量)。您的 useEffect 然后再次触发,再次调用 setCurrentUser,依此类推,导致无限循环。

为防止这种情况发生,您应该设置一个变量列表,useEffect 应该在触发前侦听这些变量。您可以通过将第二个参数传递给 useEffect.

来完成此操作
useEffect(() => {
  // your function call
}, [/* list of state/prop variables to respond to */])

如果你希望useEffect只触发一次,类似于componentDidMount,你可以传递一个空数组。

来自docs

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

在您的情况下,您似乎希望将 user 放入此数组中,因为这是您的 firestore 调用所依赖的唯一变量。如果 user.uid 没有改变,则没有理由再次触发此效果。