首页 > 解决方案 > React Native - 将道具从一个屏幕传递到另一个屏幕(使用标签导航器进行导航)

问题描述

我需要将数据从我的 HomeScreen 传递到我的 SecondScreen。如果我单击 HomeScreen 上的按钮导航到 SecondScreen,有很多示例说明如何执行此操作,但是如果我使用 v2 底部选项卡导航器,则找不到任何显示如何传递到 SecondScreen 的内容从 HomeScreen 到 SecondScreen。我尝试了 screenprops 和其他几种方法,花了大约 8 个小时试图弄清楚但无法让它工作。知道怎么做吗?拜托,任何提示都会很棒。这是我的代码:

MainTabNavigator.js:

 const config = Platform.select({
  web: { headerMode: 'screen' },
  default: {},
});


const HomeStack = createStackNavigator(
  {
    Home: HomeScreen,

  },
  config

);

HomeStack.navigationOptions = {
  tabBarLabel: 'Home',
  tabBarIcon: ({ focused }) => (
    <MaterialIcons name="home" size={32}  />
  ),
};

HomeStack.path = '';


const SecondStack= createStackNavigator(
  {
    Second: SecondScreen,
  },
  config
);    

SecondStack.navigationOptions = {
  tabBarLabel: 'Second screen stuff',

  tabBarIcon: ({ focused }) => (
    <MaterialIcons name="SecondScreenIcon" size={32}  />
  ),
};

SecondStack.path = '';


const tabNavigator = createBottomTabNavigator({
  HomeStack,
  SecondScreen
});

tabNavigator.path = '';

export default tabNavigator;

HomeScreen.js:

  class HomeScreen extends Component {

  constructor(props){
    super(props);  
  }

 componentDidMount(){

   this.setState({DataFromHomeScreen: 'my data that Im trying to send to SecondScreen'})

  }

//....

SecondScreen.js:

class SecondScreen extends Component {

      constructor(props){
        super(props);  
      }


   render()
   return(     

         <View>{this.props.DataFromHomeScreen}</View>

    )


    //....

****请在下面找到我尝试过的事情:****

HomeScreen.js:当我这样做时,它首先接收它,然后传递 null

render(){

return(
<View>
 //all of my home screen jsx
<SecondScreen screenProps={{DataFromHomeScreen : 'data im trying to pass'}}/>
</View>
)
}

MaintTabNavigator.js:当我这样做时,它首先接收它,然后传递 null

HomeStack.navigationOptions = {
  tabBarLabel: 'Home',
  tabBarIcon: ({ focused }) => (
    <MaterialIcons name="home" size={32}  />
  ),
};

<HomeStack screenProps={{DataFromHomeScreen:'data im trying to pass'}}/>


HomeStack.path = '';

我也尝试了其他 5 种方法,但我现在都不记得了。我不想在第二个屏幕中再次调用我的数据库来获取用户信息。我认识的人都不知道反应或反应本机。https://reactnavigation.org/docs/en/stack-navigator.html上的 React Native 文档充其量是最少的,仅显示以下内容:

const SomeStack = createStackNavigator({
  // config
});

<SomeStack
  screenProps={/* this prop will get passed to the screen components as this.props.screenProps */}
/>

即使您转到文档中的示例并搜索“screenprop”一词,您也不会在任何一个示例中看到任何有关屏幕道具功能的提及。我看到的所有问题都只解决了如何在按钮点击时传递道具,这很容易。我正在尝试做的事情可能吗?我敢肯定,我不是唯一一个使用标签导航器在主屏幕中检索数据并需要将其传递到其他屏幕的人。任何建议都有帮助。谢谢。

附言。这是调用主屏幕的登录类:

class SignInScreen extends React.Component {
static navigationOptions = {
  title: 'Please sign in',
};


render() {
  return (


    <View
    style={styles.container}
    contentContainerStyle={styles.contentContainer}>

    <View>
    <SocialIcon
    title='Continue With Facebook'
    button
    type='facebook'
    iconSize="36"
    onPress={this._signInAsync} 
    />
    </View>

  );
}


_signInAsync = async () => {

    let redirectUrl = AuthSession.getRedirectUrl();
    let result = await AuthSession.startAsync({
      authUrl:
        `https://www.facebook.com/v2.8/dialog/oauth?response_type=token` +
        `&client_id=${FB_APP_ID}` +
        `&redirect_uri=${encodeURIComponent(redirectUrl)}`,
    });      

    var token = result.params.access_token
    await AsyncStorage.setItem('userToken', token);

    await fetch(`https://graph.facebook.com/me?fields=email,name&access_token=${token}`).then((response) => response.json()).then((json) => {

          this.props.navigation.navigate('Home',
          {
              UserName : json.name,
              FBID : json.id,
              email : json.email

          });     


    }) .catch(() => {
       console.log('ERROR GETTING DATA FROM FACEBOOK')
      });

};
 }

export default SignInScreen;

标签: reactjsreact-nativereact-native-tabnavigator

解决方案


我认为您在 HomeScreen 组件中的 componentDidMount 中调用数据库(我是对的?)并且因为同一层次结构中的另一个组件需要相同的数据,您应该考虑将其包装到一个新组件中并调用您的父组件中的数据,然后将数据传递给所有需要它的子组件。这是做事的反应方式。HomeScreen 的状态不应包含数据,您的数据应位于更高层次结构的父组件中,并将数据作为道具传递给子组件。

这样,当您创建选项卡时,您可以按照 react native 文档的建议传递道具:

import { createBottomTabNavigator, BottomTabBar } from 'react-navigation-tabs';

const TabBarComponent = (props) => (<BottomTabBar {...props} />);

const TabScreens = createBottomTabNavigator(
{
  tabBarComponent: props =>
    <TabBarComponent
      {...props}
      style={{ borderTopColor: '#605F60' }}
    />,
 },
);

另一种解决方案可能是使用 Redux 或类似的全局状态管理。

我希望这有帮助。

编辑:

class Home extends React.Component{
 constructor(props){
   super(props);
   this.state = {data: null}
 }
 componentDidMount() {
   //get your props from navigation (your facebook credentials)
   //your call to database
   this.setState({data: yourResponseData});
 }
 render(){
   const TabNavigator = createBottomTabNavigator(
     {
       HomeScreen: props =>
         <HomeScreenStack
           {...this.state.data}
         />,
       SecondStack: props =>
         <SecondStack
           {...this.state.data}
         />,
      },
     );
   return(
     <TabNavigator />
   )
 }
}

const App = createAppContainer(Home);

export default App;

推荐阅读