首页 > 解决方案 > React Navigation 5.x 版:将状态和功能传递给所有屏幕

问题描述

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

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 道具?

谁能帮我解决这些问题?

标签: react-nativejwtreact-native-androidreact-propsreact-navigation-v5

解决方案


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

在这里阅读更多


推荐阅读