【问题标题】:React Navigation version 5.x : Passing states and function to all screensReact Navigation 5.x 版:将状态和功能传递给所有屏幕
【发布时间】:2020-10-13 06:20:14
【问题描述】:

我正在尝试在我的具有持久用户授权的本机应用程序中配置反应导航。

const Stack = createStackNavigator();

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      jwt: '',
      id:'',
      loading: true,
    };
    this.deleteItem = deviceStorage.deleteItem.bind(this);
    this.loadItem = deviceStorage.loadItem.bind(this);
    this.loadItem();
  }

  newJWT = (jwt) => {
    this.setState({jwt});
  };
  newID = (id) => {
    this.setState({id});
  }
 
 componentDidMount(){
    this.loadItem();
  }
  
  render() {
   if (!this.state.jwt) {
      return (
        <NavigationContainer>
          <Stack.Navigator headerMode='null'>
          <Stack.Screen name="Login" component={LoginScreen}/>
          <Stack.Screen name="Signup" component={SignUpScreen}/>
          </Stack.Navigator>
        </NavigationContainer>
      );
    } else {
      return (
        <NavigationContainer>
          <Stack.Navigator headerMode='null'>
           <Stack.Screen name="AuthHome" component={AuthHomeScreen}/>
          </Stack.Navigator>
        </NavigationContainer>
      );
    }
  }
}

我需要将 jwt 和用户 ID 传递给所有经过身份验证的屏幕,并将 newJWT 等函数传递给 LoginScreen。所以我可以使用该函数来更新 jwt 和用户 ID。

我不想使用 React Hooks 或 Redux 来构建这个应用程序。

  1. 我不知道如何将 jwt 和 id 传递给所有经过身份验证的屏幕
  2. 如果通过了,我需要知道如何访问 LoginScreen 中的 jwt,id 属性?

谁能帮我解答这些问题?

【问题讨论】:

  • 这样您就可以在 Asyncstorage 上保存用户 ID 和 jwt 并随时获取
  • @AkilaDevinda 我已经在 Asyncstorage 中保存了用户 ID 和 jwt 令牌。我需要在每个屏幕中为 API 请求获取 jwt 令牌和用户 ID。如果我这样做不会有性能问题?

标签: react-native jwt react-native-android react-props react-navigation-v5


【解决方案1】:

你可以在 React Native 中使用 React Context Provider。这可以防止使用 props,并允许您将变量和函数传递给提供程序内部的任何组件。

阅读更多here

【讨论】:

  • 谢谢。是的,我看到了 React Context Provider。但是无论如何我可以像在具有 screenprops 的 React Navigation 4 中那样通过?
  • @KavishkaGamage 不幸的是,不,他们删除了有利于 Context 因为 props 有 Context 没有的缺点。
猜你喜欢
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 2020-05-27
相关资源
最近更新 更多