将道具从根组件传递到AppNavigator

时间:2019-07-08 17:41:00

标签: react-native react-navigation react-apollo

我在App根组件内部有一个AppNavigator。我需要在AppNavigator中更改initialRouteName,具体取决于根组件的道具。在用户登录时在根组件中,我将证书保存在钥匙串中。我需要这样做: userLoggedIn?主页屏幕:AuthScreen 您能告诉我如何从根App组件向AppNavigator发送userLoggedIn道具吗?

App.js:

import React, { useState, useEffect } from 'react'
import { ApolloProvider } from 'react-apollo'
import { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks'
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { InMemoryCache } from 'apollo-cache-inmemory'
import * as Keychain from 'react-native-keychain'
import AppNavigator from './AppNavigator'

const httpLink = createHttpLink({
  uri: 'http://localhost:4000'
})

const authLink = setContext(async (_, { headers }) => {
  const tokens = await Keychain.getGenericPassword()
  const accessToken = tokens.accessToken
  return {
    headers: {
      ...headers,
      authorization: accessToken ? `Bearer ${accessToken}` : ''
    }
  }
})

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
  connectToDevTools: true
})

const App = () => {
  const [loggedIn, setLoggedIn] = useState(false)
  useEffect(async () => {
    const tokens = await Keychain.getGenericPassword()
    const accessToken = tokens.accessToken
    if (accessToken) {
      setLoggedIn(true)
    }
  })
  return (
    <ApolloProvider client={client}>
      <ApolloHooksProvider client={client}>
        <AppNavigator userLoggedIn={loggedIn} />
      </ApolloHooksProvider>
    </ApolloProvider>
  )
}

export default App

AppNavigator.js:

import { createStackNavigator, createAppContainer } from 'react-navigation'
import { HomeScreen, AuthScreen } from './screens'

const AppNavigator = createStackNavigator(
  {
    AUTH_SCREEN: AuthScreen,
    HOME: HomeScreen
  },
  {
    initialRouteName: 'AUTH_SCREEN',
    headerMode: 'none'
  }
)

export default createAppContainer(AppNavigator)

1 个答案:

答案 0 :(得分:1)