React Native Redux 应用程序中的条件渲染失败

Condition rendering failing in React Native Redux App

我正在尝试根据用户是否登录有条件地呈现我的 redux 应用程序。我的代码的相关和精简版本如下:

let isLoggedIn = false;

export default function App() {
  console.log('App executing...');
  console.log('isLoggedIn: ', isLoggedIn);
  return (
    <Provider store={store}>
      <NavigationContainer>
        {isLoggedIn ? ContactsTab() : Login()}
      </NavigationContainer>
    </Provider>
  );
}

store.subscribe(() => {
  // Set isLoggedIn to true if token is received and reinvoke App()
  if (store.getState().user.token) {
    isLoggedIn = true;
    App();
  }
});

该应用程序以控制台日志记录 isLoggedIn: false 开始并显示 Login()(如预期)。当我使用正确的凭据登录 phone 时,App() 被重新调用控制台日志记录 isLoggedIn: true(如预期) 但它仍然显示 Login()。如果我在应用程序函数中设置 isLoggedIn = true,应用程序会成功开始显示 ContactsTab().

这里发生了什么?当 isLoggedIn 的值成功更改为 true 时,为什么我的应用程序没有移动到 ContactsTab()?我该如何解决这个问题?

感谢您的阅读。在过去的 2 天里,我一直在尝试调试它,但没有成功,所以非常感谢任何帮助!

What is happening here? Why is my app not moving to ContactsTab() when the value of isLoggedIn successfully changes to true? How can I fix this?

重新调用应用不一定会重新呈现您的屏幕。您的条件调用无法正常工作,因为您的 render 方法只被调用一次,要修复它,您需要更改 App 组件的状态。你只是通过你的 reducer 改变状态,但你并没有在你的应用程序组件中听到那个变化。您必须监听该更改,并且根据该更改,您需要将登录状态设置为 true,然后您的组件将为您执行渲染。

阅读有关州的更多信息 here。 详细了解如何使用 redux 让组件监听应用程序状态的变化 here

这里需要像这样使用useState,useState会在state变化时自动渲染

export default function App() {
  const [isLoggedIn, setLoggedIn] = useState(false);
  console.log('App Executing...');
  console.log('isLoggedIn: ', isLoggedIn);
  store.subscribe(() => {
    // Set isLoggedIn to true if token is received and reinvoke App()
    if (store.getState().user.token) {
      setLoggedIn(true);
    }
  });
  return (
    <Provider store={store}>
      <NavigationContainer>
        {isLoggedIn ? ContactsTab() : Login()}
      </NavigationContainer>
    </Provider>
  );
}

希望对您有所帮助!