【问题标题】:React Native Firebase onAuthStateChanged with conditional rendering give warning Can't perform a React state update带有条件渲染的 React Native Firebase onAuthStateChanged 给出警告 Can't perform a React state update
【发布时间】:2020-09-10 19:47:58
【问题描述】:

React Native 应用程序在关闭并重新打开时发出警告:无法对未安装的组件执行 React 状态更新。似乎是我的条件渲染导致了这种情况,如果我删除了启动画面部分,那就没问题了。

renderScreens() 在渲染堆栈之前建立 Firebase 连接时的初始屏幕。这可行,但我不断收到警告,要求清理 useEffect 函数。

if (auth.initializing) {
  return <RootStack.Screen name={'Splash'} component={SplashScreen} />;
}
return auth.user && !auth.loading ? (
  <RootStack.Screen name={'MainStack'} component={MainStackNavigator} />
) : (
  <RootStack.Screen name={'AuthStack'} component={AuthStackNavigator} />
);

在我的身份验证钩子中

const [initializing, setInitializing] = useState<boolean>(true);
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);

useEffect(() => {
  auth().onAuthStateChanged(userState => {
    setUser(userState);
    if (initializing) setInitializing(false);
  });
}, []);

尝试使用unmount 技巧但没有帮助。下面是 react-native-firebase 的示例

// Handle user state changes
  function onAuthStateChanged(user) {
    setUser(user);
    if (initializing) setInitializing(false);
  }

  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber; // unsubscribe on unmount
  }, []);

在应用程序打开时,获取 auth.user 对象时总是会有短暂的延迟,如果删除了初始屏幕,那么让经过身份验证的用户看到身份验证屏幕然后在加载用户对象后立即更改为 main 是很奇怪的应用程序。我怎样才能正确处理这个问题而不引起警告。

【问题讨论】:

    标签: reactjs react-native firebase-authentication react-hooks


    【解决方案1】:

    我现在不确定警告部分,但要避免这种情况的一件事:if splash screen is removed, then it's weird to have authenticated user to see the auth screen 是将用户详细信息存储在某种本地存储中。我不记得 localstorage 的 react native 等价物,但在我的 React 应用程序中我这样做:

    const [newUser, setNewUser] = useState(JSON.parse(localStorage.getItem('authUser')))

    我直接从localstorage 拉出用户。这解决了我在登录用户看到登录屏幕时看到的“闪烁”,因为onAuthStateChanged 需要更长的时间才能启动。

    然后您可以在用户注销时删除localStorage。啊,我只记得是AsyncStorage。将有可能实现相同的功能:https://reactnative.dev/docs/asyncstorage

    如果您需要更多帮助,请告诉我!

    【讨论】:

    • 我将 AsyncStorage 用于稍后经过身份验证的用户配置文件部分。但我认为 Firebase 身份验证已经实现了它自己的本地存储?每当我调用onAuthStateChange 时,它都会拉取本地保存的用户对象?
    猜你喜欢
    • 2019-10-29
    • 2020-01-15
    • 2020-06-28
    • 2020-05-15
    • 2021-05-05
    • 2022-01-11
    • 2021-03-25
    • 2022-06-10
    • 2022-06-10
    相关资源
    最近更新 更多