已导入反应导航,但未定义

时间:2019-03-25 23:27:06

标签: reactjs react-native react-redux firebase-authentication react-navigation

我的react-native应用程序使用react-redux和react-navigation。

App.js导入Main组件。在Main内部,导入了反应导航并定义了所有导航器。但是,我仍然在that.navigation.navigate('Auth')的{​​{1}}上收到 TypeError:未定义不是对象(正在评估'that.navigation.navigate')]

我也尝试过Main,但得到了找不到变量:导航。导入反应导航并在同一文件中使用它是一种不好的做法吗?我想在navigation.navigate('Auth')中使用导航,以避免在每个屏幕中调用Main

App.js

firebase.auth().onAuthStateChanged

Main.js

...

const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Main />
      </Provider>
    );
  }
}

export default App;

2 个答案:

答案 0 :(得分:0)

我不确定,因为我从未使用过反应导航 但是似乎只包装了AppContainer和他的孩子,没有包装主组件,这就是为什么在这里未定义导航的原因。 您应该重新考虑组件架构的顺序


表格https://facebook.github.io/react-native/docs/navigation

  

每个屏幕组件都可以设置导航选项,例如标题。它可以使用navigation道具上的动作创建者链接到其他屏幕

您的Main组件不是屏幕,您不能在其中使用导航。

您可以执行以下操作:

const AppContainer = isAuthentified => createAppContainer(createStackNavigator(
 {
  Home: HomeStack,
  Auth: AuthStack
 },
 {initialRouteName: !!isAuthentified ? 'Home' : 'Auth'}
)); 


class Main extends React.Component {
  constructor(props) {
   super(props);
   state = {loading: false};
  }

  componentDidMount = () => {
   let tmpuser = false; 
   firebase.auth().onAuthStateChanged(async function(user) {
    if (user) {
        tmpuser = await that.props.getUserProfile(user.uid);
    }});
   this.setState({user: tmpuser, loading: false})
  }

  render() {
   if (!this.state.loading) 
    return (
     <div>{AppContainer(this.state.user)}</div>
    );
   else return (<div>loading</div>);
  }
}

//可能不完美,在智能手机上完成

答案 1 :(得分:0)

你有道具。

更改that.navigation.navigate('Auth');that.props.navigation.navigate('Auth');

相关问题